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) res = [] for _ in range(T): a, p = map(int, input().split()) if not S[p]: res.append(-1) else: if a % p == 0: res.append(0) else: res.append(1) print('\n'.join(map(str, res)))