Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Combinatorics Modulo a Prime

Binomials, Lucas’s theorem, Catalan numbers and inclusion–exclusion.

How many ways are there to choose half of a million items, modulo 109+710^9 + 7? One linear pass that tabulates factorials and their inverses answers this, and every other binomial query up to a million, in O(1)O(1). When nn outgrows the prime, Lucas's theorem takes over, and a few classic identities turn whole families of counting DPs into formulas.

What you’ll learn

  • Precompute factorials and inverse factorials modulo a prime in O(n+log⁡p)O(n + \log p) time, prove the backward recurrence for the inverses, and answer binomial queries in O(1)O(1).
  • State and prove Lucas's theorem, and derive from it the parity of binomial coefficients; relate it to Kummer's carry theorem.
  • Derive the Catalan numbers by the reflection principle and by the first-return decomposition, and recognize them in parentheses, trees and triangulations.
  • Count with inclusion–exclusion (derangements, surjections, bounded sums) and count objects up to symmetry with Burnside's lemma.

Factorials and inverse factorials

python
P = 10**9 + 7

def build(N):
    fact = [1] * (N + 1)
    for i in range(1, N + 1):
        fact[i] = fact[i - 1] * i % P
    inv_fact = [1] * (N + 1)
    inv_fact[N] = pow(fact[N], P - 2, P)       # one exponentiation (Fermat)
    for i in range(N, 0, -1):
        inv_fact[i - 1] = inv_fact[i] * i % P  # (i-1)!^-1 = i * (i!)^-1
    return fact, inv_fact

fact, inv_fact = build(10**6)

def binom(n, k):                               # needs 0 <= n <= N < P
    if k < 0 or k > n:
        return 0
    return fact[n] * inv_fact[k] % P * inv_fact[n - k] % P

O(N+log⁡P)O(N + \log P) preprocessing, then O(1)O(1) per query. binom(10**6, 5 * 10**5) returns 996692777. Computing each inverse factorial by its own exponentiation would cost O(Nlog⁡P)O(N \log P) instead.

DerivationWhy the backward pass is right, and all inverses in O(N)
  1. (i−1)!⋅(i⋅(i!)−1)=i!⋅(i!)−1≡1(modp)(i-1)! \cdot \big(i \cdot (i!)^{-1}\big) = i! \cdot (i!)^{-1} \equiv 1 \pmod p

    Since i!=i⋅(i−1)!i! = i \cdot (i-1)!, the residue i⋅(i!)−1i \cdot (i!)^{-1} is an inverse of (i−1)!(i-1)!:

  2. p=⌊p/i⌋⋅i+(p mod i)  ⟹  0≡⌊p/i⌋⋅i+(p mod i)(modp)p = \lfloor p/i \rfloor \cdot i + (p \bmod i) \;\Longrightarrow\; 0 \equiv \lfloor p/i \rfloor \cdot i + (p \bmod i) \pmod p

    So one exponentiation for (N!)−1(N!)^{-1} and NN multiplications give every inverse factorial. The inverse of a single i≤Ni \le N is then i−1=(i−1)!⋅(i!)−1i^{-1} = (i-1)! \cdot (i!)^{-1}. A second classic identity gives all of 1−1,…,N−11^{-1}, \dots, N^{-1} in O(N)O(N) directly: divide pp by ii,

  3. i−1≡−⌊p/i⌋⋅(p mod i)−1(modp)i^{-1} \equiv -\lfloor p/i \rfloor \cdot (p \bmod i)^{-1} \pmod p

    and multiply by i−1(p mod i)−1i^{-1} (p \bmod i)^{-1}, which exists because 0<p mod i<i0 < p \bmod i < i for a prime p>i≥2p > i \ge 2:

Check your understanding

For which modulus does fact[n] * inv_fact[k] * inv_fact[n - k] compute (nk)\binom{n}{k} correctly for every 0≤k≤n≤1060 \le k \le n \le 10^6?

  1. 2322^{32}
  2. 999,983999{,}983, a prime
  3. 109+710^9 + 7, a prime
  4. 10910^9
Show the answer

C. 109+710^9 + 7, a prime

The formula needs every factorial up to 10610^6 to be invertible: the modulus must be a prime larger than 10610^6, and 109+710^9 + 7 is. 999,983999{,}983 is prime but smaller than 10610^6, so 999,983!999{,}983! and every larger factorial are ≡0\equiv 0.

Lucas’s theorem

DerivationProof with polynomials
  1. (1+x)p≡1+xp,and by induction(1+x)pi≡1+xpi(1+x)^p \equiv 1 + x^p, \qquad\text{and by induction}\qquad (1+x)^{p^i} \equiv 1 + x^{p^i}

    For 0<j<p0 < j < p, the prime pp divides (pj)=p!j! (p−j)!\binom{p}{j} = \frac{p!}{j!\,(p-j)!}: it divides the numerator but not the denominator. So, as polynomials with coefficients modulo pp,

  2. (1+x)n=∏i((1+x)pi)ni≡∏i(1+xpi)ni=∏i∑ji=0ni(niji)xjipi(1+x)^n = \prod_i \big((1+x)^{p^i}\big)^{n_i} \equiv \prod_i \big(1 + x^{p^i}\big)^{n_i} = \prod_i \sum_{j_i=0}^{n_i} \binom{n_i}{j_i} x^{j_i p^i}

    Split the exponent nn by its base-pp digits:

  3. (nk)≡∏i(niki)(modp)\binom{n}{k} \equiv \prod_i \binom{n_i}{k_i} \pmod p

    Compare the coefficients of xkx^k. On the left it is (nk)\binom{n}{k}. On the right, a product of terms has exponent ∑ijipi\sum_i j_i p^i with every ji≤ni<pj_i \le n_i < p, and base-pp representations are unique, so only ji=kij_i = k_i for all ii contributes, and nothing at all if some ki>nik_i > n_i:

Parity. For p=2p = 2 every digit factor is (00)\binom00, (10)\binom10, (11)\binom11 (all 1) or (01)=0\binom01 = 0. So (nk)\binom{n}{k} is odd exactly when every 1-bit of kk is also a 1-bit of nn: when kk is a submask of nn, k & ~n == 0 in code. Row nn of Pascal's triangle therefore has 2popcount⁡(n)2^{\operatorname{popcount}(n)} odd entries (Glaisher, 1899), and the triangle modulo 2 draws the Sierpiński triangle.

Kummer's theorem (1852) says more: the exponent of pp in (a+ba)\binom{a+b}{a} equals the number of carries when aa and bb are added in base pp. Take a=ka = k and b=n−kb = n - k: adding them without any carry means ni−ki≥0n_i - k_i \ge 0 in every digit, which is exactly when no factor of Lucas's product is zero.

Catalan numbers

How many strings of nn pairs of balanced parentheses are there? Read "(" as a step up and ")" as a step down: a balanced string is a Dyck path, a walk of 2n2n steps from height 0 back to height 0 that never goes below 0. There are (2nn)\binom{2n}{n} walks with nn steps of each kind; the problem is to subtract the ones that dip below 0.

DerivationThe reflection principle
  1. #{walks 0→0 touching −1}=#{walks 0→−2}\#\{\text{walks } 0 \to 0 \text{ touching } -1\} = \#\{\text{walks } 0 \to -2\}

    A bad walk touches height −1-1. Reflect the part of it after its first touch of −1-1 in the line at height −1-1: up steps become down steps there, so the walk now ends at height −2-2, with n−1n - 1 up steps and n+1n + 1 down steps.

  2. Cn=(2nn)−(2nn+1)C_n = \binom{2n}{n} - \binom{2n}{n+1}

    The map is a bijection: every walk ending at −2-2 touches −1-1, and reflecting it again after its first touch restores the original. So

  3. Cn=1n+1(2nn)1,1,2,5,14,42,132,429,1430,…C_n = \frac{1}{n+1}\binom{2n}{n} \qquad 1, 1, 2, 5, 14, 42, 132, 429, 1430, \dots

    Since (2nn+1)=(2nn)⋅nn+1\binom{2n}{n+1} = \binom{2n}{n}\cdot\frac{n}{n+1}:

The same numbers come out of a counting DP. A nonempty balanced string splits uniquely as (A)B(A)B: AA is the part inside the parenthesis that matches the first one, BB is the rest, and both are balanced. This first-return decomposition is a unique decomposition, so

Cn+1=∑i=0nCi Cn−i,C0=1,C_{n+1} = \sum_{i=0}^{n} C_i\, C_{n-i}, \qquad C_0 = 1,

an O(n2)O(n^2) DP. Modulo a prime, the formula with the factorial table is faster: Cn=(2nn)⋅(n+1)−1C_n = \binom{2n}{n} \cdot (n+1)^{-1} in O(1)O(1) per value. Asymptotically Cn∼4n/(n3/2π)C_n \sim 4^n / (n^{3/2}\sqrt{\pi}).

Objects of size nnDecomposition matching (A)B(A)B
Balanced strings of nn pairs of parenthesesthe first pair and what it encloses, then the rest
Binary trees with nn nodes; BST shapes on nn keysthe root's left subtree and right subtree
Triangulations of a convex polygon with n+2n + 2 sidesthe triangle on one fixed side splits off two smaller polygons
Full parenthesizations of a product of n+1n + 1 factorsthe last multiplication splits the factors in two
Monotone lattice paths that never cross the diagonalthe first return to the diagonal
Catalan numbers in a few of their guises; Stanley's book on them lists 214. The parenthesizations are the candidate solutions of matrix-chain multiplication: there are about 4n4^n of them, which is why that problem needs an interval DP over its O(n2)O(n^2) subproblems instead.
Predict before you look

How many differently shaped binary search trees can hold the keys 1,2,3,4,51, 2, 3, 4, 5?

Show the answer

42 trees

Choose the root rr: the keys below it form the left subtree and the keys above it the right one, so the count is C5=C0C4+C1C3+C2C2+C3C1+C4C0=14+5+4+5+14=42C_5 = C_0C_4 + C_1C_3 + C_2C_2 + C_3C_1 + C_4C_0 = 14 + 5 + 4 + 5 + 14 = 42.

Inclusion–exclusion

DerivationProof: count each object once
  1. ∑j=0t(−1)j(tj)=(1−1)t={1t=00t≥1\sum_{j=0}^{t} (-1)^j \binom{t}{j} = (1 - 1)^t = \begin{cases} 1 & t = 0 \\ 0 & t \ge 1 \end{cases}

    An object with exactly tt of the bad properties is counted once in N(S)N(S) for each SS among those tt properties, with sign (−1)∣S∣(-1)^{\abs{S}}. Its total contribution is

  2. #{objects with no bad property}=∑j=0m(−1)j(mj)Nj\#\{\text{objects with no bad property}\} = \sum_{j=0}^{m} (-1)^j \binom{m}{j} N_j

    When the properties are symmetric, N(S)N(S) depends only on j=∣S∣j = \abs{S}, and the 2m2^m terms collapse to m+1m + 1:

CountBad property AiA_iFormulaExample
Derangements: permutations of nn with no fixed pointii stays in placeDn=∑j(−1)j(nj)(n−j)!D_n = \sum_j (-1)^j \binom{n}{j} (n-j)!D4=9D_4 = 9, D10=1,334,961D_{10} = 1{,}334{,}961; DnD_n is the integer nearest n!/en!/e
Surjections of nn items onto kk labelslabel ii is unused∑j(−1)j(kj)(k−j)n\sum_j (-1)^j \binom{k}{j} (k-j)^nn=5n = 5, k=3k = 3: 243−96+3=150243 - 96 + 3 = 150
Solutions of x1+⋯+xk=nx_1 + \dots + x_k = n with 0≤xi≤c0 \le x_i \le cxi≥c+1x_i \ge c + 1∑j(−1)j(kj)(n−j(c+1)+k−1k−1)\sum_j (-1)^j \binom{k}{j} \binom{n - j(c+1) + k - 1}{k - 1}without the bound: (n+k−1k−1)\binom{n+k-1}{k-1}, "stars and bars"
Integers in [1,N][1, N] coprime to 3030divisible by the ii-th prime of 2, 3, 5N−∑⌊N/p⌋+∑⌊N/pq⌋−⌊N/30⌋N - \sum \lfloor N/p \rfloor + \sum \lfloor N/pq \rfloor - \lfloor N/30 \rfloorN=100N = 100: 100−103+32−3=26100 - 103 + 32 - 3 = 26
Inclusion–exclusion in four classic forms. Binomials and factorials come from the table of the first step, so each symmetric count costs O(m)O(m) after preprocessing. Without symmetry the sum has 2m2^m terms, enumerated as bitmasks; when N(S)N(S) is itself a sum over subsets, the sum-over-subsets transform computes all of them in O(2mm)O(2^m m).
Check your understanding

In how many ways can three distinguishable dice show a total of 10?

  1. 36
  2. 33
  3. 27
  4. 21
Show the answer

C. 27

Set yi=xi−1∈[0,5]y_i = x_i - 1 \in [0, 5], so y1+y2+y3=7y_1 + y_2 + y_3 = 7. Stars and bars gives (92)=36\binom{9}{2} = 36; a die with yi≥6y_i \ge 6 leaves 11 to share, (32)=3\binom{3}{2} = 3 ways, for each of the 3 dice; two dice cannot both reach 6. So 36−3⋅3=2736 - 3 \cdot 3 = 27.

Counting up to symmetry: Burnside’s lemma

How many different necklaces of 6 beads can be made from black and white beads, if turning a necklace around its center does not make a new one? There are 26=642^6 = 64 colorings, but most necklaces correspond to 6 of them and some to fewer, so dividing by 6 is wrong. The right tool averages over the symmetries.

DerivationProof by double counting
  1. ∑g∈G∣Fix⁡(g)∣=∑x∈X∣Stab⁡(x)∣\sum_{g \in G} \abs{\operatorname{Fix}(g)} = \sum_{x \in X} \abs{\operatorname{Stab}(x)}

    Count the pairs (g,x)(g, x) with g⋅x=xg \cdot x = x, first by gg, then by xx, where Stab⁡(x)\operatorname{Stab}(x) is the set of gg fixing xx:

  2. ∑x∈X∣G∣∣Orb⁡(x)∣=∣G∣⋅#orbits\sum_{x \in X} \frac{\abs{G}}{\abs{\operatorname{Orb}(x)}} = \abs{G} \cdot \#\text{orbits}

    By the orbit–stabilizer theorem, ∣Stab⁡(x)∣=∣G∣/∣Orb⁡(x)∣\abs{\operatorname{Stab}(x)} = \abs{G} / \abs{\operatorname{Orb}(x)}, so each orbit OO contributes ∑x∈O∣G∣/∣O∣=∣G∣\sum_{x \in O} \abs{G}/\abs{O} = \abs{G}:

Necklaces. The rotation by rr positions splits the nn positions into gcd⁡(r,n)\gcd(r, n) cycles, and it fixes a coloring exactly when the coloring is constant on each cycle: kgcd⁡(r,n)k^{\gcd(r,n)} colorings for kk colors. Exactly φ(d)\varphi(d) rotations have gcd⁡(r,n)=n/d\gcd(r, n) = n/d, for each divisor dd of nn, which gives

N(n,k)=1n∑r=0n−1kgcd⁡(r,n)=1n∑d∣nφ(d) kn/d.N(n, k) = \frac{1}{n}\sum_{r=0}^{n-1} k^{\gcd(r, n)} = \frac{1}{n}\sum_{d \mid n} \varphi(d)\, k^{n/d}.

For 6 beads in 2 colors, the six rotations fix 64,2,4,8,4,264, 2, 4, 8, 4, 2 colorings, so there are 84/6=1484/6 = 14 necklaces. Allowing reflections too (the dihedral group of 12 symmetries) leaves 13 bracelets.

Key takeaways

  • Modulo a prime p>np > n, a factorial table, one exponentiation for (N!)−1(N!)^{-1} and the backward pass (i−1)!−1=i⋅(i!)−1(i-1)!^{-1} = i \cdot (i!)^{-1} give every (nk)\binom{n}{k} in O(1)O(1).
  • Lucas's theorem, (nk)≡∏i(niki)(modp)\binom{n}{k} \equiv \prod_i \binom{n_i}{k_i} \pmod p, follows from (1+x)p≡1+xp(1+x)^p \equiv 1 + x^p; modulo 2 it says (nk)\binom{n}{k} is odd iff kk is a submask of nn.
  • Cn=(2nn)/(n+1)C_n = \binom{2n}{n}/(n+1) counts Dyck paths, binary trees, triangulations and parenthesizations: reflection proves the formula, and the first-return decomposition gives Cn+1=∑iCiCn−iC_{n+1} = \sum_i C_i C_{n-i}.
  • Inclusion–exclusion counts the objects with no bad property as ∑S(−1)∣S∣N(S)\sum_S (-1)^{\abs{S}} N(S), and Burnside's lemma counts objects up to symmetry as the average number of fixed points.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

You have fact[0..N] and inv_fact[N] = pow(fact[N], P - 2, P). Which loop fills the rest of the inverse factorials correctly?

  1. inv_fact[i - 1] = inv_fact[i] * i % P, for i=N,…,1i = N, \dots, 1
  2. inv_fact[i] = inv_fact[i - 1] * i % P, for i=1,…,Ni = 1, \dots, N
  3. inv_fact[i - 1] = inv_fact[i] * (i - 1) % P, for i=N,…,1i = N, \dots, 1
  4. inv_fact[i - 1] = inv_fact[i] // i, for i=N,…,1i = N, \dots, 1
Show the answer

A. inv_fact[i - 1] = inv_fact[i] * i % P, for i=N,…,1i = N, \dots, 1

(i−1)!⋅i⋅(i!)−1=i!⋅(i!)−1≡1(i-1)! \cdot i \cdot (i!)^{-1} = i! \cdot (i!)^{-1} \equiv 1, so (i−1)!−1≡i⋅(i!)−1(i-1)!^{-1} \equiv i \cdot (i!)^{-1}: walk down from NN, multiplying by ii.

Question 2

How many entries of row 13 of Pascal's triangle, (130),…,(1313)\binom{13}{0}, \dots, \binom{13}{13}, are odd?

  1. 14
  2. 7
  3. 3
  4. 8
Show the answer

D. 8

13=1101213 = 1101_2 has three 1-bits. By Lucas's theorem modulo 2, (13k)\binom{13}{k} is odd iff kk is a submask of 13, and there are 23=82^3 = 8 submasks: k=0,1,4,5,8,9,12,13k = 0, 1, 4, 5, 8, 9, 12, 13.

Question 3

In how many ways can the product A1A2A3A4A5A_1 A_2 A_3 A_4 A_5 be fully parenthesized?

  1. 42
  2. 24
  3. 14
  4. 5
Show the answer

C. 14

A product of n+1n + 1 factors has CnC_n full parenthesizations: the last multiplication splits it into two smaller products. With five factors, C4=14C_4 = 14.

Question 4

How many necklaces of 4 beads, each one of 3 colors, are there if two necklaces that differ by a rotation count as the same?

  1. 81
  2. 24
  3. 21
  4. 27
Show the answer

B. 24

Burnside's lemma averages the fixed colorings over the 4 rotations: the identity fixes 34=813^4 = 81, the half-turn 32=93^2 = 9, the two quarter-turns 33 each. (81+3+9+3)/4=24(81 + 3 + 9 + 3)/4 = 24.

Further reading

  • É. Lucas, "Théorie des fonctions numériques simplement périodiques," American Journal of Mathematics 1 (1878).
  • A. Granville, "Arithmetic properties of binomial coefficients I: binomial coefficients modulo prime powers," Organic Mathematics, CMS Conference Proceedings 20 (1997).
  • R. P. Stanley, Catalan Numbers (Cambridge University Press, 2015).
  • P. M. Neumann, "A lemma that is not Burnside's," The Mathematical Scientist 4 (1979).
  • L. G. Valiant, "The complexity of computing the permanent," Theoretical Computer Science 8 (1979).