MOD = 10**9 + 7 m = 5*10**6 + 5 fac = [0] * m finv = [0] * m inv = [0] * m def COMBinitialize(m): fac[0] = 1 finv[0] = 1 if m > 1: fac[1] = 1 finv[1] = 1 inv[1] = 1 for i in range(2, m): fac[i] = fac[i-1] * i % MOD inv[i] = MOD - inv[MOD % i] * (MOD // i) % MOD finv[i] = finv[i - 1] * inv[i] % MOD COMBinitialize(m) def main(): import sys input = sys.stdin.buffer.readline def Eratosthenes(x: int) -> set: """x以下の素数の集合を返す""" from math import sqrt sup = int(x) primes = {i for i in range(2, sup+1)} for i in range(2, int(sqrt(sup+1))+1): if i in primes: mul = 2 while i*mul <= sup: primes.discard(i*mul) mul += 1 return primes primes = Eratosthenes(5*10**6 + 5) T = int(input()) for _ in range(T): A, P = (int(i) for i in input().split()) if P not in primes: print(-1) continue A %= P ans = pow(A, fac[A] % P, P) print(ans) if __name__ == '__main__': main()