from collections import defaultdict import math def Sieve_of_Eratosthenes(maxA): lst = [-1]*(maxA+1) lst[0] = 0 lst[1] = 1 for i in range(2, maxA+1): if lst[i] == -1: for g in range(i, maxA+1, i): if lst[g] == -1: lst[g] = i return lst def is_prime(n): d = defaultdict(int) now = n while True: if now == lst[now]: if now != 1: d[now] += 1 break r = lst[now] while now % r == 0: now //= r d[r] += 1 if d[r] > 1 or len(d) > 1: return False if len(d) == 1: return True else: return False maxA = 5*10**6 + 1 lst = Sieve_of_Eratosthenes(maxA) t = int(input()) for _ in range(t): a, p = map(int, input().split()) if is_prime(p): if math.gcd(a, p) == 1: print(1) else: print(0) else: print(-1)