import sys input = sys.stdin.readline def sieve(n): res = [True for _ in range(n + 1)] res[0] = False res[1] = False i = 2 while i * i <= n: if res[i]: for j in range(i * 2, n + 1, i): res[j] = False i += 1 return res T = int(input()) S = sieve(5 * 10**6) for _ in range(T): a, p = map(int, input().split()) if not S[p]: print(-1) else: if a % p == 0: print(0) else: print(1)