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

long long aps(long long x){
    if(x>=0)return x;
    else return -x;

}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);


   int t;
   cin>>t;
   for(int t1=0;t1<t;t1++){
        int n,m;
        cin>>n>>m;
        long long p,x,g1,g2;
        cin>>p;
        for(int i=1;i<n;i++){
            cin>>x;
            if(i==1)g1=aps(x-p);
            else g1=__gcd(g1,aps(x-p));

        }

        for(int i=0;i<m;i++){
            cin>>x;
            if(i==0)g2=__gcd(g1,aps(x-p));
            else g2=__gcd(g1 , __gcd(g1 , g2/__gcd(g2,aps(x-p))) *__gcd( g1,(aps(x-p)) ) );

        }
        if(g1==g2)cout<<"0"<<endl;
        else cout<<"1"<<endl;


   }

return 0;
}