For C (n, m) mod p. Here the N,m,p (P is the prime number) are very large cases. The formula for C (n, m) = C (n-1,m) + C (n-1, m-1) can no longer be recursive.
The Lusac theorem is used here.
For non-negative integers m and N and a prime p, the following congruence relation holds:
where
and
is the base p expansions of m and n respectively.
For a separate C (NI, MI) mod p, the known C (n, m) mod p = n!/(m! ( N-M)!) MoD p. Obviously, the division takes the mold, and here we use the m!. (n-m)! The inverse of the element.
According to Fermat theorem:
Known (A, p) = 1, then ap-1≡1 (mod p), so a*ap-2≡1 (mod p).
i.e. (m! ( N-M)!) The inverse is (m! ( N-M)!) P-2;
Code:
#include <iostream>
using namespace Std;
typedef long Long LL;
ll Exp_mod (ll A, ll B, ll P) { ll res = 1; while (b! = 0) { if (b&1) res = (res * a)% P; A = (a*a)% p; b >>= 1; } return res;} ll Comb (ll A, ll B, ll p) { if (a < b) return 0; if (a = = b) return 1; if (b > a) b = a A; LL ans = 1, CA = 1, cb = 1; for (LL i = 0; i < b; ++i) { CA = (CA * (a-i))%p; CB = (CB * (b-i))%p; } Ans = (Ca*exp_mod (CB, P-2, p))% P; return ans;} ll Lucas (int n, int m, int p) { ll ans = 1; while (N&&m&&ans) { ans = (Ans*comb (n%p, m%p, p))% P; n/= p; M/= p; } return ans;} int main () { Read (); int n, m, p; while (~SCANF ("%d%d%d", &n, &m, &p)) { printf ("%lld\n", Lucas (N, M, p)); } return 0;}
[To] combination number modulus Lucas theorem