#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

int main()
{
    int T, N, M;
    cin >> T;
    for(int i = 0; i < T; i++){
        cin >> N >> M;

        long long minDev, a, b;
        int waste = 0;
        bool X = true;
        cin >> a >> b;
        minDev = abs(a - b);
        for(int y = 2; y < N; y++){
            a = b;
            cin >> b;
            if (abs(a - b) % minDev != 0){
                minDev = __gcd(abs(a - b), minDev);
                if (minDev == 1) {
                    cout << 0 << endl;
                    X = false;
                    waste = N - y - 1;
                    break;
                }
            }
        }

        a = b;
        if(X) for (int y = 0; y < M; y++){
            cin >> b;
            if (abs(a - b) % minDev == 0){
                cout << 0 << endl;
                X = false;
                waste = M - y - 1;
                break;
            }
        }
        else while (M + waste > 0) {
            cin >> b;
            waste--;
        }

        if(X) cout << 1 << endl;
        else {
            while (waste > 0){
                cin >> b;
            waste--;
            }
        }
    }
    return 0;
}