import sys def input(): return sys.stdin.readline()[:-1] is_prime = [False for _ in range(5000001)] for i in range(2, 5000001): if not is_prime[i]: is_prime[i] = True for j in range(2*i, 5000001, i): is_prime[j] = True else: is_prime[i] = False for _ in range(int(input())): a, p = list(map(int, input().split())) if is_prime[p]: print((-a)%p) else: print(-1)