N = 5*(10**6)+1 E = [0 for _ in range(N)] for i in range(2,N): for j in range(i,N,i): E[j] += 1 T = int(input()) for _ in range(T): A,P = map(int,input().split()) if E[P] != 1: print(-1) else: if E[A%P] == 1: print(1) else: print(0)