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


int n;
int a[MAXN], b[2*MAXN];

int calc(int of){
    vector<int> v = {0};
    for(int i = 2; i <= n; ++i){
        int tmp = a[i] - a[1];
        int p = (b[1+of] + tmp) % m;
        v.push_back(dif(b[i],p));
    }
    //for(int k : v) cout << k << ' '; cout << '\n';
    sort(v.begin(), v.end());
    int ln = v.size();
    int tmp = v[ln/2];
    int ans = 0;
    for(int i = 0; i < ln; ++i){
        v[i] -= tmp;
        ans += abs(v[i]);
    }
    return ans;
}

long long Konflikt(int32_t N,int32_t M,int32_t *A,int32_t *B){
    n = N;
    m = M;
    if(n > 2000) 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;
}