T = int(input())

C = 5 * 10 ** 6
dat = [0] * C
prime = set()
i = 2
while i < C:
    if dat[i] == 0:
        prime.add(i)
        j = 2 * i
        while j < C:
            dat[j] = 1
            j += i
    i += 1
for _ in range(T):
    a,p = map(int,input().split())
    if p in prime:
        if a % p == 0:print(0)
        else:print(1)
    else:
        print(-1)