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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include <bits/stdc++.h> using namespace std;
typedef long long ll; typedef pair<ll, ll> Equation;
ll exgcd(ll a, ll b, ll &x, ll &y) { if (!b) { x = 1, y = 0; return a; } ll d = exgcd(b, a % b, y, x); y -= a / b * x; return d; }
ll inv(ll a, ll p) { ll ans, tmp; exgcd(a, p, ans, tmp); return (ans % p + p) % p; }
ll qmul(ll a, ll b, ll p) { ll res = 0; while (b) { if (b & 1) res = (res + a) % p; a = (a + a) % p; b >>= 1; } return res % p; }
ll qpow(ll a, ll b, ll p) { ll res = 1; while (b) { if (b & 1) res = (res % p * a % p) % p; a = (a * a) % p; b >>= 1; } return res % p; }
ll mul(initializer_list<ll> args, ll p) { __int128 res = 1; for (ll i: args) { res = (res % p * i % p) % p; } return (ll) (res % p); }
ll CRT(vector<Equation> &v) { ll M = 1; ll res = 0; for (Equation eq: v) M *= eq.second; for (Equation i: v) { ll Mi = M / i.second; res = (res + qmul(qmul(i.first, Mi, M), inv(Mi, i.second), M)) % M; } return res % M; }
ll resolve(ll a, ll p, ll ppow) { if (!a) return 1; ll s = 1; for (ll i = 1; i <= ppow; i++) { if (i % p) s = mul({s, i}, ppow); } s = qpow(s, a / ppow, ppow); for (ll i = a / ppow * ppow + 1; i <= a; i++) { if (i % p) s = mul({s, i}, ppow); } return mul({s, resolve(a / p, p, ppow)}, ppow); }
ll getA(ll n, ll m, ll p, ll ppow) { ll x = 0, y = 0, z = 0; for (ll i = n; i; i /= p) x += i / p; for (ll i = m; i; i /= p) y += i / p; for (ll i = n - m; i; i /= p) z += i / p; return mul({ qpow(p, x - y - z, ppow), resolve(n, p, ppow), inv(resolve(m, p, ppow), ppow), inv(resolve(n - m, p, ppow), ppow) }, ppow); }
ll exLucas(ll n, ll m, ll p) { vector<Equation> E; for (ll i = 2; i * i <= p; i++) { if (p % i == 0) { ll c = 1; while (p % i == 0) { c *= i; p /= i; } E.emplace_back(getA(n, m, i, c), c); } } if (p > 1) E.emplace_back(getA(n, m, p, p), p); return CRT(E); }
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
ll n, m, p; cin >> n >> m >> p; cout << exLucas(n, m, p) << endl;
return 0; }
|