#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 5005;
int m;
int dif(int a, int b){return (a-b+m)%m;}


int n;
int a[MAXN], b[2*MAXN];
array<int,2> d[MAXN];
array<int,2> f[MAXN];

void upd(int i, int t){
    vector<array<int,2>> v = {{d[i][0]-t,0},{d[i][1]-t,1},{t-d[i][0],2},{t-d[i][1],3}};
    sort(v.begin(), v.end());
    int idx = 0;
    while(v[idx][0] < 0) ++idx;
    if(v[idx][1] == 0) f[i] = {-1,d[i][0]};
    if(v[idx][1] == 1) f[i] = {-1,d[i][1]};
    if(v[idx][1] == 2) f[i] = {1,-d[i][0]};
    if(v[idx][1] == 3) f[i] = {1,-d[i][1]};
}

int calc(int of){
    //vector<int> v = {0};
    map<int,vector<int>> mp;
    d[1] = {0,0};
    mp[1].push_back(1);
    f[1] = {-1,0};
    for(int i = 2; i <= n; ++i){
        //v.push_back(dif(a[i],a[1])-dif(b[i+of],b[1+of]));
        int tmp = a[i] - a[1];
        int p = (b[1+of] + tmp) % m;
        d[i][0] = dif(b[i+of],p);
        d[i][1] = (m-d[i][0])%m;
        mp[d[i][0]+1].push_back(i);
        mp[d[i][1]+1].push_back(i);
        mp[(d[i][0]+d[i][1])/2].push_back(i);
        f[i] = {-1,min(d[i][0],d[i][1])};
    }
    array<int,2> ff = {0,0};
    for(int i = 1; i <= n; ++i){
        ff[0] += f[i][0];
        ff[1] += f[i][1];
    }
    mp[1e9] = {};
    int last = -1e9, ans = 1e18;
    for(auto &p : mp){
        int t = p.first-1;
        //cout << "p " << t << '\n';
        if(ff[0] < 0) ans = min(ans, ff[0]*t + ff[1]);
        else ans = min(ans, ff[0]*last + ff[1]);
        //cout << ans << '\n';
        for(auto k : p.second){
            ff[0] -= f[k][0];
            ff[1] -= f[k][1];
            upd(k, t+1);
            ff[0] += f[k][0];
            ff[1] += f[k][1];
        }
        last = t+1;
    }
    return ans;
}

long long Konflikt(int32_t N,int32_t M,int32_t *A,int32_t *B){
    n = N;
    m = M;
    if(n > 500) return 0;
    for(int i = 1; i <= n; ++i){
        a[i] = A[i];
        b[i] = B[i];
    }
    sort(a+1, a+n+1);
    sort(b+1, b+n+1);
    for(int i = 1; i <= n; ++i){
        b[n+i] = b[i];
    }
    int ans = 1e18;
    for(int i = 0; i < n; ++i){
        ans = min(ans, calc(i));
    }
    return ans;
}
#undef int

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;
}