#include <iostream>
#define llint long long
#define inf 1000000000000000

using namespace std;

llint n, m;
llint a[1005], b[1005];
llint dp[1005][1005];

int main(void)
{
  while(1){
    cin >> n >> m;
    if(n == 0 && m == 0) break;

    for(int i = 1; i <= n; i++) cin >> a[i], a[i]--;
    for(int i = 1; i <= n; i++) cin >> b[i], b[i]--;
    for(int i = 1; i <= n; i++) a[i] = (b[i]-a[i]+m) % m;

    for(int i = 1; i <= n; i++){
      for(int j = 0; j <= n; j++){
        dp[i][j] = inf;
      }
    }
    dp[1][0] = a[1];

    for(int i = 1; i < n; i++){
      for(int j = 0; j <= n; j++){
        if(a[i]+j*m >= a[i+1]+j*m){
          dp[i+1][j] = min(dp[i+1][j], dp[i][j]);
          if(j+1 <= n) dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j] + (a[i+1]+(j+1)*m) - (a[i]+j*m));
        }
        else{
          if(j > 0) dp[i+1][j-1] = min(dp[i+1][j-1], dp[i][j]);
          dp[i+1][j] = min(dp[i+1][j], dp[i][j] + (a[i+1]+j*m) - (a[i]+j*m));
        }
      }
    }

    llint ans = inf;
    for(int i = 0; i <= n; i++) ans = min(ans, dp[n][i]);
    cout << ans << endl;
  }

  return 0;
}

