#include <map>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
const int N = 1e6 + 10;
typedef long long ll;
map<int, int> id;
struct edge {
int v, next, w;
} E[N << 3];
int p[N << 3], cnt;
inline void init() {
memset(p, -1, sizeof (p));
cnt = 0;
}
inline void insert(int u, int v, int w) {
E[cnt].w = w;
E[cnt].v = v;
E[cnt].next = p[u];
p[u] = cnt++;
}
int a[N], b[N], st[N], vis[N], tn, tp;
ll dis[N];
priority_queue<pair<ll, int> > pq;
ll Dij(int s, int t) {
memset(dis, 0x3f, sizeof (dis));
dis[s] = 0;
pq.emplace(-dis[s], s);
while (!pq.empty()) {
auto r = pq.top();
pq.pop();
int u = r.second;
if (vis[u]) continue;
vis[u] = 1;
for (int i = p[u], v; i + 1; i = E[i].next) {
v = E[i].v;
if (dis[v] > dis[u] + E[i].w) {
dis[v] = dis[u] + E[i].w;
pq.emplace(-dis[v], v);
}
}
}
return dis[t];
}
int main() {
init();
int n, m;
scanf("%d%d", &n, &m);
tn = n;
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
if (!id[m - a[i]]) id[m - a[i]] = ++tn, st[++tp] = m - a[i];
insert(i, id[m - a[i]], 0);
}
for (int i = 1; i <= n; ++i) {
scanf("%d", &b[i]);
if (!id[b[i]]) id[b[i]] = ++tn, st[++tp] = b[i];
insert(id[b[i]], i, 0);
}
sort(st + 1, st + tp + 1);
for (int i = 1; i < tp; ++i) insert(id[st[i]], id[st[i + 1]], (st[i + 1] - st[i]) % m);
insert(id[st[tp]], id[st[1]], (m + st[1] - st[tp]) % m);
printf("%lld\n", Dij(1, n));
return 0;
}