T = int(input()) C = 5 * 10 ** 6 dat = [0] * C prime = set() prime.add(2) for i in range(4,C,2): dat[i] = 1 i = 3 while i < C: if dat[i] == 0: prime.add(i) j = 2 * i while j < C: dat[j] = 1 j += i i += 2 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)