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:

  1. Extract the power of separately with Legendre’s formula:
  2. Compute the -free factorial — the product of integers not divisible by — modulo , recursively:
  3. 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

MethodCost
primefactorial + inverse factorial tables per query
primeLucas
anygeneralised Lucas (Granville)
compositeanyfactor + CRTas above per factor
anyneed onlyLegendre’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

  1. Not reducing before multiplyingfact[n] * invFact[k] can exceed long long if either is unreduced. Take % MOD after every multiplication.
  2. or must return 0, not garbage from a negative index.
  3. 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