Computing and — the case analysis depends entirely on how relates to .
Case 1: prime, — the standard setup
Precompute factorials and inverse factorials once:
const int MOD = 1e9 + 7, N = 1e6 + 5;
long long fact[N], invFact[N];
void init() {
fact[0] = 1;
for (int i = 1; i < N; i++) fact[i] = fact[i-1] * i % MOD;
invFact[N-1] = powmod(fact[N-1], MOD - 2, MOD);
for (int i = N-1; i > 0; i--) invFact[i-1] = invFact[i] * i % MOD;
}
long long C(int n, int k) {
if (k < 0 || k > n) return 0;
return fact[n] * invFact[k] % MOD * invFact[n-k] % MOD;
}preprocessing with one modular exponentiation, then per binomial. This is the single most-used snippet in competitive programming.
Case 2: prime,
trivially (the product contains ). The interesting quantity is , which is not always 0.
Lucas’ theorem
Write and in base : , . Then
long long lucas(long long n, long long k, long long p) {
long long res = 1;
while (n || k) {
long long ni = n % p, ki = k % p;
if (ki > ni) return 0;
res = res * C(ni, ki) % p; // small binomial, precomputed
n /= p; k /= p;
}
return res;
}per query after precomputing factorials up to . Practical for .
Corollary (Kummer): is divisible by iff adding and in base produces a carry.
Case 3: , a prime power
Use the generalised Lucas / Andrew Granville method:
- Extract the power of separately with Legendre’s formula:
- Compute the -free factorial — the product of integers not divisible by — modulo , recursively:
- Recombine.
Uses Wilson’s theorem to evaluate the block product. .
Case 4: arbitrary composite
Factor , apply case 3 to each prime power, and recombine with the CRT. Practical when every is small enough to precompute.
The decision table
| Method | Cost | ||
|---|---|---|---|
| prime | factorial + inverse factorial tables | per query | |
| prime | Lucas | ||
| any | generalised Lucas (Granville) | ||
| composite | any | factor + CRT | as above per factor |
| any | need only | Legendre’s formula | |
| , | — | precompute; the common case |
Trailing zeros and divisibility
Number of trailing zeros of = — there are always more factors of 2 than of 5. See Trailing Zeroes.
In base : factor and take .
Binomials without division
When the modulus is awkward, Pascal’s identity gives an table with only additions:
Valid for any modulus, including composites where inverses do not exist. Practical for .
Common pitfalls
Three recurring bugs
- Not reducing before multiplying —
fact[n] * invFact[k]can exceedlong longif either is unreduced. Take% MODafter every multiplication.- or must return 0, not garbage from a negative index.
- Assuming an inverse exists. With a composite modulus,
powmod(x, MOD-2)is meaningless. Use the prime-power method.
See also: Lucas Theorem · Combinatorics · Wilson’s Theorem