1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <bits/stdc++.h> using LL = long long; const int N = 1e7 + 100; int n, m, P, ans; int fac[N], pr[N], cnt, imp[N], mp[N]; bool vis[N]; int qpow(int x, int y) { int res = 1; for (; y; y >>= 1, x = LL(x) * x % P) if (y & 1) res = LL(res) * x % P; return res; } void prev() { fac[0] = fac[1] = 1; for (int i = 2; i < N; ++i) fac[i] = LL(fac[i - 1]) * i % P; for (int i = 2; i < N; ++i) { if (!vis[i]) pr[++cnt] = i; for (int j = 1; j <= cnt && LL(pr[j]) * i < N; ++j) { vis[pr[j] * i] = true; if (i % pr[j] == 0) break; } } for (int i = 1, j = 1, sum = 1, is = 1; i < N; ++i) { if (pr[j] == P) ++j; if (j <= cnt && pr[j] <= i) sum = LL(pr[j++]) * sum % P, is = qpow(sum, P - 2); imp[i] = is; } for (int i = 1, j = 1, sum = 1; i < N; ++i) { if (j <= cnt && pr[j] <= i) sum = LL(pr[j++] - 1) * sum % P; mp[i] = sum; } } int main() { int T; scanf("%d %d", &T, &P); prev(); while (T--) { scanf("%d %d", &n, &m); if (n >= P && m < P) puts("0"); else { ans = LL(fac[n]) * imp[m] % P * mp[m] % P; printf("%d\n", ans); } } return 0; }
|