#include #include #include using namespace std; using ll = long long; int main() { ll n, m; cin >> n >> m; vector a(n), b(n); for (ll i = 0; i < n; i++) cin >> a[i]; for (ll i = 0; i < n; i++) { cin >> b[i]; b[i] += m - a[i]; b[i] %= m; } b.insert(b.begin(), 0); b.push_back(0); vector db(n + 1); ll plus = 0; for (ll i = 0; i < n + 1; i++) { db[i] = (m + b[i + 1] - b[i]) % m; plus += b[i + 1] >= b[i]; } ll ans = 0; sort(db.begin(), db.end()); for (ll i = 0; i < plus; i++) { ans += db[i]; } cout << ans << endl; return 0; }