import math MAXX = 5*10**6 + 5 isprime = [1]*(MAXX) #theratos for num in range(2, MAXX): if isprime[num]: for k in range(num*2, MAXX, num): isprime[k] = 0 T = int(input()) for tt in range(T): A, P = map(int, input().split()) if isprime[P]: print(P - (A % P)) else: print(-1)