|
| 1 | +#include <bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +typedef long long ll; |
| 6 | +typedef long double ld; |
| 7 | +typedef vector<int> vi; |
| 8 | +typedef vector<vector<int> > vvi; |
| 9 | +typedef pair<int, int> pii; |
| 10 | + |
| 11 | +#define erep(i, x, n) for (auto i = x; i<=(ll)(n); i++) |
| 12 | +#define rep(i, x, n) for(auto i = x; i<(ll)(n); i++) |
| 13 | +#define all(v) ((v).begin()), ((v).end()) |
| 14 | +#define sz(v) ((int)((v).size())) |
| 15 | +#define mod(n, m) ((n%m + m) % m) |
| 16 | +#define reset(n, m) memset(n, m, sizeof n) |
| 17 | +#define endl '\n' |
| 18 | + |
| 19 | +int power(int x, unsigned int y, int p) |
| 20 | +{ |
| 21 | + int res = 1; // Initialize result |
| 22 | + x = x % p; // Update x if it is more than or |
| 23 | + // equal to p |
| 24 | + while (y > 0) |
| 25 | + { |
| 26 | + // If y is odd, multiply x with result |
| 27 | + if (y & 1) |
| 28 | + res = (res * 1ll * x) % p; |
| 29 | + |
| 30 | + // y must be even now |
| 31 | + y = y >> 1; // y = y/2 |
| 32 | + x = (x * 1ll * x) % p; |
| 33 | + } |
| 34 | + return res; |
| 35 | +} |
| 36 | + |
| 37 | +// Function to find modular inverse of a under modulo p |
| 38 | +// using Fermat's method. Assumption: p is prime |
| 39 | +int modInverse(int a, int p) |
| 40 | +{ |
| 41 | + return power(a, p - 2, p); |
| 42 | +} |
| 43 | + |
| 44 | +// Returns n! % p using Wilson's Theorem |
| 45 | +int modFact(int n, int p) |
| 46 | +{ |
| 47 | + // n! % p is 0 if n >= p |
| 48 | + if (p <= n) |
| 49 | + return 0; |
| 50 | + |
| 51 | + // Initialize result as (p-1)! which is -1 or (p-1) |
| 52 | + int res = (p - 1), den = 1; |
| 53 | + |
| 54 | + // Multiply modulo inverse of all numbers from (n+1) |
| 55 | + // to p |
| 56 | + for (int i = n + 1; i < p; i++) |
| 57 | + res = (res * 1ll * i) % p; |
| 58 | + return res * modInverse(den, p - 2); |
| 59 | +} |
| 60 | + |
| 61 | +int main() |
| 62 | +{ |
| 63 | + ios_base::sync_with_stdio(0); |
| 64 | + cin.tie(0); |
| 65 | + |
| 66 | + int tc; |
| 67 | + cin >> tc; |
| 68 | + while (tc--) |
| 69 | + { |
| 70 | + int n, m; |
| 71 | + cin >> n >> m; |
| 72 | + cout << modFact(n, m) << endl; |
| 73 | + } |
| 74 | + return 0; |
| 75 | +} |
0 commit comments