#include <bits/stdc++.h>

using namespace std;
using i64 = long long;
const i64 INF = i64(1e18) + 7;

bool chmax(i64& x, i64 y){
    if(x < y){
        x = y;
        return true;
    }
    return false;
}
bool chmin(i64& x, i64 y){
    if(x > y){
        x = y;
        return true;
    }
    return false;
}

bool solve(){
    int n, m;
    cin >> n >> m;
    if(!n)
        return false;
    vector<i64> a(n), b(n), v(n);
    for(auto& x : a)
        cin >> x;
    for(auto& x : b)
        cin >> x;
    for(int i = 0; i < n; ++i){
        v[i] = (b[i] - a[i] + m) % m;
        assert(0 <= v[i] && v[i] < m);
    }
    vector<vector<i64>> dp(n, vector<i64>(n + 2, INF));
    for(int i = 0; i < n; ++i)
        dp[0][i] = v[0] + m * i;
    for(int i = 0; i < n - 1; ++i){
        for(int j = 0; j <= n; ++j){

            chmin(dp[i + 1][j], dp[i][j] + max(0LL, v[i + 1] - v[i]));
            chmin(dp[i + 1][j], dp[i][j + 1]);
            chmin(dp[i + 1][j + 1], dp[i][j] + max(0LL, v[i + 1] + m - v[i]));
            /*
            chmin(dp[i + 1][0], dp[i][0] + max(0LL, v[i + 1] - v[i]));
            chmin(dp[i + 1][0], dp[i][1] + max(0LL, v[i + 1] + - (v[i] + m)));
            chmin(dp[i + 1][1], dp[i][0] + max(0LL, v[i + 1] + m - v[i]));
            chmin(dp[i + 1][1], dp[i][1] + max(0LL, v[i + 1] + m - (v[i] + m)));
            */
        }
    }
    i64 ans = INF;
    for(auto& x : dp.back())
        chmin(ans, x);
    cout << ans << endl;
    return true;
}

signed main()
{
    while(solve());
    return 0;
}

