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

#define pb push_back
#pragma GCC optimize("O3")

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

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];
    for(int i=1;i<=n;++i)
        ob[i]=b[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 i=1;i<=n;++i){
            ll dod=m-a[i];
            a[i]=(a[i]+dod)%m;
            b[i]=(b[i]+dod)%m;
        }
        sort(b+1,b+n+1);
        ll plf=0,prt=0,pmd=0;
        ll c1=0,s1=0;
        ll c2=0,s2=0;
        ll c3=0,s3=0;
        ll c4=0,s4=0;
        for(int i=1;i<=n;++i){
            ++c4;
            s4+=b[i];
        }
        for(int i=1;i<=n;++i){
            ll x=b[i];
            while(prt+1<=n&&b[prt+1]<=(2*x+m)/2){
                ++prt;
                s4-=b[prt];--c4;
                s3+=b[prt];++c3;
            }
            while(pmd+1<=n&&b[pmd+1]<=x){
                ++pmd;
                s3-=b[pmd];--c3;
                s2+=b[pmd];++c2;
            }
            while(plf+1<=n&&b[plf+1]<=(2*x-m)/2){
                ++plf;
                s2-=b[plf];--c2;
                s1+=b[plf];++c1;
            }
            ll cur=0;
            cur+=c1*(m-x)+s1;
            cur+=c2*x-s2;
            cur+=s3-c3*x;
            cur+=c4*(m+x)-s4;
            ans=min(ans,cur);
        }
    }
    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;
}
*/