def f(n,MOD): r = 1%MOD if n >= MOD: return 0 if n <= 1000000: for i in range(1,n+1): r *= i r %= MOD return r for i in range(2,int(MOD**0.5)+1): if MOD%i==0: return 0 r = 1 for i in range(n+1,MOD): r *= i r %= MOD return (-pow(r,MOD-2,MOD))%MOD T = int(input()) for _ in range(T): n,MOD = map(int,input().split()) print(f(n,MOD))