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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include <bits/stdc++.h> #define LL long long using namespace std; const int N = 1e5 + 5, D = 40; int n, p, l, r, phi; int pr[N], inv[N], fac[N], c[N][D], cnt = 0; int qpow(int x, int y) { int res = 1; while (y) { if (y & 1) res = (LL)res * x % p; x = (LL)x * x % p; y >>= 1; } return res; } void prev() { phi = p; fac[0] = inv[0] = fac[1] = inv[1] = 1; int t = p; for (int i = 2; i <= t / i; ++i) { if (t % i) continue; phi = (LL)phi / i * (i - 1); pr[++cnt] = i; while (!(t % i)) t /= i; } if (t > 1) pr[++cnt] = t, phi = (LL)phi / t * (t - 1); for (int i = 2; i <= n; ++i) { t = i; for (int j = 1; j <= cnt; ++j) { c[i][j] = c[i - 1][j]; while (!(t % pr[j])) t /= pr[j], ++c[i][j]; } fac[i] = (LL)fac[i - 1] * t % p; inv[i] = qpow(fac[i], phi - 1); } } int C(int x, int y) { if (y < 0 || x < y || n <= 0) return 0; if (!y) return 1; int res = (LL)fac[x] * inv[y] % p * inv[x - y] % p; for (int i = 1; i <= cnt; ++i) res = (LL)res * qpow(pr[i], c[x][i] - c[y][i] - c[x - y][i]) % p; return res; } int main() { scanf("%d %d %d %d", &n, &p, &l, &r); prev(); int ans = 0; r = min(r, n); for (int i = 0; i <= n - l; ++i) { int t = ((LL)C(n - i, (n - i - l) >> 1) - C(n - i, (n - i - r - 1) >> 1) + p) % p; ans = (ans + (LL)t * C(n, i) % p) % p; } printf("%d\n", ans); return 0; }
|