#include <bits/stdc++.h>
using namespace std;
typedef long long ll;


vector<int>solve2(const vector<int>&v,int from){
	vector<int>que;
	map<int,int>mp;
	for(int x=from;x<v.size();++x){
		if(mp.find(v[x])==mp.end()){
			que.emplace_back(v[x]);
			mp[v[x]]=que.size()-1;
		}else{
			while(true){
				int aback=que.back();
				
				mp.erase(aback);
				que.pop_back();
				if(aback==v[x])break;
			}
		}
	}
	return que;
}
vector<int> solve(int N,long long int K,vector<int>v,int start){
	
	vector<int>rs(N);

	{
		map<int,int>mp;
		for(int i=N-1;i>=0;--i){
			mp[v[i]]=N+i;
		}
		for(int i=N-1;i>=0;--i){
			rs[i]=mp[v[i]];
			mp[v[i]]=i;
		}
	}
	

	long long int ny=0,nx=start;
	map<int,long long int>mp;
	mp[start]=0;
	while(true){
		//cout<<nx<<ny<<endl;
		auto next_x=rs[nx];
		long long next_y=ny;
		//cout<<next_x<<' '<<next_y<<endl;
		if(next_x>=N){
			next_y++;
			next_x-=N;
		}
		next_x++;
		if(next_x>=N){
			next_y++;
			next_x-=N;
		}
		if(next_y>=K){
			
			if(K-1==next_y){
				v.insert(v.end(),v.begin(),v.end());
			}
			return solve2(v,nx);
		}else{
			ny=next_y;
			nx=next_x;

			if(mp.find(nx)==mp.end()){
				mp[nx]=ny;
			}else{
				long long sa=-(mp[nx]-ny);
				long long int rest=K-ny;
				rest%=sa;
				//cout<<rest<<endl;
				if(rest==0)rest=sa;

				long long xx=K%sa;
				if(xx==0)xx=sa;
				assert(nx==0);
				return solve(N,xx,v,0);
			}
		}
	}
	assert(false);
	
}
#define WHATS(var) cout<<#var<<"="<<var<<endl;
int main() {
	ios::sync_with_stdio(false);
	int N,M;cin>>N>>M;
	set<long long int>sushis,teas;
	for(int i=0;i<N;++i){
		int a;cin>>a;
		sushis.emplace(a);
		sushis.emplace(a+M);
		sushis.emplace(a+2*M);

	}
	for(int i=0;i<N;++i){
		int a;cin>>a;
		teas.emplace(a);
		teas.emplace(a+M);
		teas.emplace(a+2*M);

	}
	long long int answer=0;
	int now=0;
	for(int i=0;i<N;++i){
		auto it=sushis.lower_bound(now);

		answer+=*it-now;
		now=*it;
		now%=M;
		for(int j=0;j<3;++j){
			sushis.erase(now+j*M);
		}



		auto jt=teas.lower_bound(now);
		auto lt=jt;
		if(!sushis.empty()){
			
			auto kt=sushis.lower_bound(*jt);
			//WHATS(*kt);
			//WHATS(*teas.upper_bound(*kt));
			//WHATS(*prev(teas.upper_bound(*kt)));
			lt=prev(teas.upper_bound(*kt));
		}

		answer+=*lt-now;
		now=*lt;
		now%=M;
		for(int j=0;j<3;++j){
			teas.erase(now+M*j);
		}
	}
	cout<<answer<<endl;
	return 0;
}