def isprime(n): if n <= 1: return False elif n == 2: return True elif n % 2 == 0: return False A = [2, 325, 9375, 28178, 450775, 9780504, 1795265022] s = 0 d = n - 1 while d % 2 == 0: s += 1 d >>= 1 for a in A: if a % n == 0: return True x = pow(a, d, n) if x != 1: for t in range(s): if x == n - 1: break x = x * x % n else: return False return True def solve(n, m): if n <= 10 ** 5: p = 1 for i in range(1, n + 1): p *= i p %= m return p % m if n >= m or not isprime(m): return 0 inv = 1 for i in range(n + 1, m): inv *= i inv %= m ans = -pow(inv, m - 2, m) return ans % m for _ in range(int(input())): ans = solve(*map(int, input().split())) print(ans)