#include <bits/stdc++.h>
#define MAXN (int)5005
#define pii pair<ll,ll>
#define fi first
#define se second
using namespace std;
typedef long long ll;
ll n,m,a[MAXN],b[MAXN],r=0;
vector<ll>r1,r2;
ll f(ll rr){
    ll ox=0;
    for(int i=0;i<r1.size();i++){
        if(((ll)r1.size()-i)*(r1[i]-ox)-((ll)r2.size()+i)*(r1[i]-ox)<0){
            break;
        }
        rr-=((ll)r1.size()-i)*(r1[i]-ox)-((ll)r2.size()+i)*(r1[i]-ox);
        ox=r1[i];
    }
    return rr;
}
ll check(){
    ll rez=0;
    for(int i=1;i<=n;i++){
        rez+=abs(a[i]-b[v2[i-1]]);
    }
    return rez;
}
ll perm(int x){
    if(x==n){
        return check();
    }
    ll rez=1e18;
    for(int i=0;i<v.size();i++){
        v2.push_back(v[i]);
        v.erase(v.begin()+i);
        rez=min(rez,perm(x+1));
        v.insert(v.begin()+i,v2.back());
        v2.pop_back();
    }
    return rez;
}
void bf(){
    r=1e18;
    for(int i=1;i<=n;i++){
        v.push_back(i);
    }
    for(int i=0;i<m-1;i++){
        for(int j=1;j<=n;j++){
            a[j]=(a[j]+1)%m;
        }
        r=min(r,perm(0));
    }
}
void solve(){
    if(n<=10&&m<=20){
        bf();
        return;
    }
    sort(a+1,a+n+1);
    sort(b+1,b+n+1);
    for(int i=1;i<=n;i++){
        if(a[i]<b[i]){
            r1.push_back(b[i]-a[i]);
        }else{
            r2.push_back(a[i]-b[i]);
        }
        r+=abs(a[i]-b[i]);
    }
    sort(r1.begin(),r1.end());
    sort(r2.begin(),r2.end());
    if(r1.size()<r2.size()){
        swap(r1,r2);
    }
    ll olr=r;
    r=f(r);
    swap(r1,r2);
    r=min(r,f(olr));
}
long long Konflikt(int N,int M,int *A,int *B){
    n=N;
    m=M;
    for(int i=1;i<=n;i++){
        a[i]=A[i];
        b[i]=B[i];
    }
    solve();
    return r;
}