#include<bits/stdc++.h>
using namespace std;
using namespace std;
int A[300005],B[300005];
int main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int T;
cin>>T;
while(T--){
int N,M;cin>>N>>M;
for(int i=0;i<N;i++)cin>>A[i];
for(int i=0;i<N;i++)cin>>B[i];
sort(A,A+N);
sort(B,B+N);
long long s1=0,s2=0;
for(int i=0;i<N;i++){
s1+=(A[i]+B[N-1-i])%M;
s2+=(A[i]+B[i])%M;
}
cout<<min(s1,s2)<<'\n';
}
return 0;
}
AC6 WA24