using System;



namespace takmicenje
{
    class Program
    {
        static void Main(string[] args)
        {
            int t = int.Parse(Console.ReadLine());
            int[] outputs = new int[t];
            for (int i = 0; i < t; i++)
            {
                string input = Console.ReadLine();
                var d = input.Split(' ');
                int N = int.Parse(d[0]);
                int M = int.Parse(d[1]);
               
                long aNzd = nzdArrayRazlikaStringToInt(Console.ReadLine().Split(' '));
                
                long bNzd = nzdArrayRazlikaStringToInt(Console.ReadLine().Split(' '));
                
                if (nzd(aNzd, bNzd) == 1)
                {
                    outputs[i] = 1;
                }
                else
                {
                    outputs[i] = 0;
                }
                
            }
            foreach (int output in outputs)
            {
                Console.WriteLine(output);
            }
            Console.ReadLine();

        }
        
        static long nzd(long a, long b)
        {
            a = Math.Abs(a);
            b = Math.Abs(b);
            long t;

            while (b != 0)
            {
                t = b;
                b = a % b;
                a = t;
            }
            return a;
        }
        
        static long nzdArrayRazlikaStringToInt(string[] a)
        {
            
            long a0 = long.Parse(a[0]);
            long currentNzd;
            if (a.Length >= 3)
            {
                currentNzd = nzd(a: a0 - long.Parse(a[1]), b: a0 - long.Parse(a[2]));
            }
            else
            {
                currentNzd = a0 - long.Parse(a[1]);
                return currentNzd;
            }
            for (int i = 3; i < a.Length; i++)
            {
                
                currentNzd = nzd(currentNzd, a0 - long.Parse(a[i]));
                
            }
            return currentNzd;
        }
    }
}