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

using namespace std;

ll nzd(ll x, ll y){
    if(y == 0)
        return x;
    else
        return nzd(y, x%y);
}

ll nzdNiza(ll a[], int n){
    ll pom = a[0];
    for(int i = 1;i < n;i++){
        pom = nzd(pom, a[i]);
        if(pom == 1) break;
    }
    return pom;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin >> t;
    int n, m;
    ll prvi, pom;
    ll nzd1, nzd2;
    for(int i = 0;i < t;i++){
        cin >> n >> m;
        ll prihvacene[n-1], odbijene[m];
        cin >> prvi;
        for(int j = 0;j < n-1;j++){
            cin >> pom;
            prihvacene[j] = abs(prvi - pom);
        }
        for(int k = 0;k < m;k++){
            cin >> pom;
            odbijene[k] = abs(prvi - pom);
        }
        nzd1 = nzdNiza(prihvacene, n-1);
        nzd2 = nzdNiza(odbijene, m);
        if(nzd1 != nzd2)
            cout << "1\n";
        else
            cout << "0\n";
    }
}