#include #include using namespace std; using int128 = __int128_t; #define rep(i, n) for (int i = 0; i < n; ++i) #define reps(i, n, s) for (int i = 0; i < n; i += s) #define repl(i, l, r) for (int i = l; i < r; ++i) #define repsl(i, l, r, s) for (int i = l; i < r; i += s) #define all(iterable) (iterable).begin(), (iterable).end() constexpr int dx4[4] = {1, 0, -1, 0}; constexpr int dy4[4] = {0, 1, 0, -1}; constexpr int dx8[8] = {1, 1, 0, -1, -1, -1, 0, 1}; constexpr int dy8[8] = {0, 1, 1, 1, 0, -1, -1, -1}; template void print(const vector& vec, const string sep = " ", const string end = "\n") { int n = vec.size(); rep(i, n) { cout << vec[i]; if (i < n - 1) cout << sep; else cout << end; } } template void read(vector& a, int begin_index, int length) { if (a.size() < begin_index + length) a.resize(begin_index + length); while (length --> 0) cin >> a[begin_index++]; } template void read(vector& a) { read(a, 0, a.size()); } // returns {x,y,g} s.t. ax+by=g=gcd(a,b)>=0. std::tuple ext_gcd(long long a, long long b) { long long x = 1, y = 0; long long z = 0, w = 1; long long tmp; while (b) { long long p = a / b, q = a % b; tmp = x - y * p; x = y; y = tmp; tmp = z - w * p; z = w; w = tmp; a = b; b = q; } if (a >= 0) return {x, z, a}; else return {-x, -z, -a}; } // returns {x,g} s.t. a*x=g (mod m) std::pair gcd_inv(long long a, long long m) { auto [x, y, g] = ext_gcd(a, m); return {x, g}; } // returns x s.t. a*x=1 (mod m) if exists, otherwise throws runtime error. long long inv_mod(long long a, long long mod) { auto [inv, y, g] = ext_gcd(a, mod); assert(g == 1); return inv; } int solve(int n, int m) { if (m <= n) return 0; if (m <= 200000) { long long fac = 1 % m; repl(i, 1, n + 1) fac = fac * i % m; return fac; } for (int i = 2; i * i <= m; ++i) { if (m % i == 0) return 0; } long long num = m - 1; long long den = 1; repl(i, n + 1, m) { den = den * i % m; } return num * inv_mod(den, m) % m; } int main() { size_t t; cin >> t; while (t --> 0) { size_t n, m; cin >> n >> m; cout << solve(n, m) << '\n'; } return 0; }