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

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

#define N 550
const ll inf=1e18;
ll a[N],b[N],n,m;
ll oa[N],ob[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;
    if(n>500)return 0;
    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];
    //1)
    //a[i]>=b[i]
    //1.1) a[i]+x<m, odnosno a[i]<m-x
    //onda ans+=x
    //1.2) a[i]+x>=m odnosno a[i]>=m-x
    //onda ti je to isto kao a[i]+(x-m)
    //odnosno a[i]-(m-x)
    //1.2.1) a[i]-(m-x)>=b[i], odnosno a[i]-b[i]>=m-x
    //onda ans-=(m-x)
    //1.2.2) a[i]-(m-x)<b[i], odnosno a[i]-b[i]<m-x
    //ans-=2*(a-b)+x-m
    //2)
    //a[i]<b[i]
    //onda oboma dodas m-1-a i imas slucaj 1
    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)
            b[i]=ob[i];
        for(int i=1;i<=n;++i){
            ll dod=m-a[i];
            a[i]=(a[i]+dod)%m;
            b[i]=(b[i]+dod)%m;
        }
        for(int j=1;j<=n;++j){
            ll x=(b[j]-a[j]+2*m)%m;
            ll cur=0;
            for(int i=1;i<=n;++i)
                cur+=min(abs(b[i]-x),abs(b[i]-(m-x))+m-x);
            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;
}
*/