def Eratosthenes(N): #N以下の素数のリストを返す N+=1 is_prime_list = [True]*N m = int(N**0.5)+1 for i in range(3,m,2): if is_prime_list[i]: is_prime_list[i*i::2*i]=[False]*((N-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,N,2) if is_prime_list[i]] N = 5*10**6 ok = [0]*(N+1) for i in Eratosthenes(N): ok[i] = 1 import sys T = int(input()) for _ in range(T): a,p = map(int,sys.stdin.readline().split()) if ok[p]==0: print(-1) else: print(1 if a%p else 0)