#include<bits/stdc++.h>
using namespace std;
using ll=long long;

#define pb push_back

#define N 5050
const ll inf=1e18;
ll a[N],b[N],n,m;
ll oa[N];

ll dst(ll x,ll y){
    return min(abs(x-y),m-abs(x-y));
}

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];
    for(int i=1;i<=n;++i)b[i]=B[i];
    sort(a+1,a+n+1);
    sort(b+1,b+n+1);
    for(int i=1;i<=n;++i){
        oa[i]=a[i];
    }
    ll ans=inf;
    for(int i=1;i<=n;++i){
        ll pnt=0;
        for(int ii=i;ii<=n;++ii)
            a[++pnt]=oa[ii];
        for(int ii=1;ii<i;++ii)
            a[++pnt]=oa[ii];
        for(int ii=1;ii<=n;++ii){
            ll x=(b[ii]-a[ii]+2*m)%m;
            ll sum=0;
            for(int j=1;j<=n;++j)
                sum+=dst((a[j]+x)%m,b[j]);
            ans=min(ans,sum);
        }
    }
    return ans;
}

#undef N

/*
int main()
{
    int N,M;
    cin >> N >> M;
    int* A = new int[N+1];
    int* B = new int[N+1];

    for (int i=1; i<=N; i++) cin >> A[i];
    for (int i=1; i<=N; i++) cin >> B[i];

    cout << Konflikt(N,M,A,B) <<endl;

    delete[] A;
    delete[] B;
    return 0;
}
*/