// {{{ Templates #include #define show(x) cerr << #x << " = " << x << endl using namespace std; using ll = long long; using pii = pair; using vi = vector; template ostream& operator<<(ostream& os, const vector& v) { os << "sz:" << v.size() << "\n["; for (const auto& p : v) { os << p << ","; } os << "]\n"; return os; } template ostream& operator<<(ostream& os, const pair& p) { os << "(" << p.first << "," << p.second << ")"; return os; } constexpr ll MOD = (ll)1e9 + 7LL; template constexpr T INF = numeric_limits::max() / 100; // }}} template T extgcd(const T a, const T b, T& x, T& y) // ax+by=gcd(a,b) { T d = a; if (b != 0) { d = extgcd(b, a % b, y, x); y -= (a / b) * x; } else { x = 1; y = 0; } return d; } inline bool isprime(const ll n) { for (ll i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } constexpr ll LIMIT = 100000; int main() { cin.tie(0); ios::sync_with_stdio(false); int T; cin >> T; for (int t = 0; t < T; t++) { ll N, M; cin >> N >> M; if (N >= M) { cout << 0 << endl; continue; } if (N <= LIMIT) { ll prod = 1; for (ll i = 1; i <= N; i++) { prod = (prod * i) % M; } cout << prod << endl; } else { if (not isprime(M)) { cout << 0 << endl; } else { ll prod = 1; for (ll i = 1; i <= M - N - 1; i++) { prod = (prod * i) % M; } ll inv = 0; ll tmp = 0; extgcd(prod, M, inv, tmp); cout << (inv * (M - 1)) % M << endl; } } } return 0; }