#include <iostream>
#include <cstdlib>
using namespace std;

int nzd(int a, int b)
{
	if (b == 0) return a;
	a = a % b;
	return nzd(b, a);
}
int main()
{
	int br;
	cin >> br;
	int t[5] = { 1,1,1,1,1};
	for (int m = 0; m < br; m++)
	{
		int p, n;
		cin >> p >> n;
		int a[75000];
		cin >> a[0] >> a[1];
		int rsk = abs(a[1] - a[0]);
		for (int i = 2; i < p; i++)
		{
			cin >> a[i];
			int rzm = abs(a[i] - a[i - 1]);
			if (nzd(rzm, rsk) > 1)
				rsk = nzd(rzm, rsk);
			if (rzm % rsk != 0)
			{
				t[m] = 0;
				break;
			}

		}
		int b[75000];
		cin >> b[0];
		for (int i = 1; i < n; i++)
		{
			cin >> b[i];
			int rzm = abs(b[i] - b[i - 1]);
			if (rzm % rsk == 0)
			{
				t[m] = 0;
				break;
			}
		}

	}
	for (int i = 0; i < br; i++)
	{
		cout << t[i] << endl;
	}
}