import math t = int(input()) m = 5000000 prime = [True for _ in range(m + 1)] prime[1] = False for x in range(2, m + 1): if not prime[x]: continue prime[x] = True for y in range(2 * x, m + 1, x): prime[y] = False ans = [] for _ in range(t): a, p = map(int, input().split()) if not prime[p]: ans.append(-1) elif math.gcd(a, p) == 1: ans.append(1) else: ans.append(0) print(*ans, sep='\n')