T = int(input()) limit = 5000000 is_prime = [True] * (limit + 1) is_prime[0] = False is_prime[1] = False for p in range(0, limit + 1): if not is_prime[p]: continue for i in range(p * p, limit + 1, p): is_prime[i] = False for i in range(T): A, P = map(int, input().split()) if is_prime[P]: if A % P == 0: print(0) else: print(1) else: print(-1)