using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp6
{
    class Program
    {
        static long gcd(long a, long b)
        {
            if (a == 0)
                return b;
            return gcd(b % a, a);
        }
        static long findGCD(long[] arr, int n)
        {
            long result = arr[0];
            for (int i = 1; i < n; i++)
            {
                result = gcd(arr[i], result);

                if (result == 1)
                {
                    return 1;
                }
            }

            return result;
        }
        static void Main(string[] args)
        {
            int T = int.Parse(Console.ReadLine());
            int[] T1 = new int[T];
            for (int i = 0; i < T; i++)
            {
                var s = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
                int N = s[0];
                int M = s[1];
                string[] A = Console.ReadLine().Split(' ');
                long[] A1 = new long[N];
                long[] A2 = new long[N-1];
                long[] B2 = new long[M - 1];
                for (int j = 0; j < N; j++)
                {
                    A1[j] = Convert.ToInt64(A[j]);
                }
                Array.Sort(A1);
                for (int j = 1; j <N; j++)
                {
                    A1[j] -= A1[0];
                    A2[j - 1] = A1[j];
                }
                long nzd = findGCD(A2, N-1);
                string[] B = Console.ReadLine().Split(' ');
                long[] B1 = new long[M];
                for (int j = 0; j < M; j++)
                {
                    B1[j] = Convert.ToInt64(B[j]);
                }
                Array.Sort(B1);
                for (int j = 1; j < M; j++)
                {
                    B1[j] -= B1[0];
                    B2[j - 1] = B1[j];
                }
                long nzd1 = findGCD(B2, M - 1);
                if(nzd1%nzd==0&&nzd1/nzd>1)
                {
                    T1[i] = 0;
                }
                else
                    T1[i] = 1;
            }
            for (int i = 0; i < T; i++)
            {
                Console.WriteLine(T1[i]);
            }
        }
    }
}