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 ? One linear pass that tabulates factorials and their inverses answers this, and every other binomial query up to a million, in . When 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 time, prove the backward recurrence for the inverses, and answer binomial queries in .
- 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
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 preprocessing, then per query. binom(10**6, 5 * 10**5) returns 996692777. Computing each inverse factorial by its own exponentiation would cost instead.
Since , the residue is an inverse of :
So one exponentiation for and multiplications give every inverse factorial. The inverse of a single is then . A second classic identity gives all of in directly: divide by ,
and multiply by , which exists because for a prime :
For which modulus does fact[n] * inv_fact[k] * inv_fact[n - k] compute correctly for every ?
- , a prime
- , a prime
Show the answer
C. , a prime
The formula needs every factorial up to to be invertible: the modulus must be a prime larger than , and is. is prime but smaller than , so and every larger factorial are .
Lucas’s theorem
For , the prime divides : it divides the numerator but not the denominator. So, as polynomials with coefficients modulo ,
Split the exponent by its base- digits:
Compare the coefficients of . On the left it is . On the right, a product of terms has exponent with every , and base- representations are unique, so only for all contributes, and nothing at all if some :
Parity. For every digit factor is , , (all 1) or . So is odd exactly when every 1-bit of is also a 1-bit of : when is a submask of , k & ~n == 0 in code. Row of Pascal's triangle therefore has odd entries (Glaisher, 1899), and the triangle modulo 2 draws the Sierpiński triangle.
Kummer's theorem (1852) says more: the exponent of in equals the number of carries when and are added in base . Take and : adding them without any carry means in every digit, which is exactly when no factor of Lucas's product is zero.
Catalan numbers
How many strings of 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 steps from height 0 back to height 0 that never goes below 0. There are walks with steps of each kind; the problem is to subtract the ones that dip below 0.
A bad walk touches height . Reflect the part of it after its first touch of in the line at height : up steps become down steps there, so the walk now ends at height , with up steps and down steps.
The map is a bijection: every walk ending at touches , and reflecting it again after its first touch restores the original. So
Since :
The same numbers come out of a counting DP. A nonempty balanced string splits uniquely as : is the part inside the parenthesis that matches the first one, is the rest, and both are balanced. This first-return decomposition is a unique decomposition, so
an DP. Modulo a prime, the formula with the factorial table is faster: in per value. Asymptotically .
| Objects of size | Decomposition matching |
|---|---|
| Balanced strings of pairs of parentheses | the first pair and what it encloses, then the rest |
| Binary trees with nodes; BST shapes on keys | the root's left subtree and right subtree |
| Triangulations of a convex polygon with sides | the triangle on one fixed side splits off two smaller polygons |
| Full parenthesizations of a product of factors | the last multiplication splits the factors in two |
| Monotone lattice paths that never cross the diagonal | the first return to the diagonal |
How many differently shaped binary search trees can hold the keys ?
Show the answer
42 trees
Choose the root : the keys below it form the left subtree and the keys above it the right one, so the count is .
Inclusion–exclusion
An object with exactly of the bad properties is counted once in for each among those properties, with sign . Its total contribution is
When the properties are symmetric, depends only on , and the terms collapse to :
| Count | Bad property | Formula | Example |
|---|---|---|---|
| Derangements: permutations of with no fixed point | stays in place | , ; is the integer nearest | |
| Surjections of items onto labels | label is unused | , : | |
| Solutions of with | without the bound: , "stars and bars" | ||
| Integers in coprime to | divisible by the -th prime of 2, 3, 5 | : |
In how many ways can three distinguishable dice show a total of 10?
- 36
- 33
- 27
- 21
Show the answer
C. 27
Set , so . Stars and bars gives ; a die with leaves to share, ways, for each of the 3 dice; two dice cannot both reach 6. So .
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 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.
Count the pairs with , first by , then by , where is the set of fixing :
By the orbit–stabilizer theorem, , so each orbit contributes :
Necklaces. The rotation by positions splits the positions into cycles, and it fixes a coloring exactly when the coloring is constant on each cycle: colorings for colors. Exactly rotations have , for each divisor of , which gives
For 6 beads in 2 colors, the six rotations fix colorings, so there are necklaces. Allowing reflections too (the dihedral group of 12 symmetries) leaves 13 bracelets.
Key takeaways
- Modulo a prime , a factorial table, one exponentiation for and the backward pass give every in .
- Lucas's theorem, , follows from ; modulo 2 it says is odd iff is a submask of .
- counts Dyck paths, binary trees, triangulations and parenthesizations: reflection proves the formula, and the first-return decomposition gives .
- Inclusion–exclusion counts the objects with no bad property as , 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.
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?
inv_fact[i - 1] = inv_fact[i] * i % P, forinv_fact[i] = inv_fact[i - 1] * i % P, forinv_fact[i - 1] = inv_fact[i] * (i - 1) % P, forinv_fact[i - 1] = inv_fact[i] // i, for
Show the answer
A. inv_fact[i - 1] = inv_fact[i] * i % P, for
, so : walk down from , multiplying by .
How many entries of row 13 of Pascal's triangle, , are odd?
- 14
- 7
- 3
- 8
Show the answer
D. 8
has three 1-bits. By Lucas's theorem modulo 2, is odd iff is a submask of 13, and there are submasks: .
In how many ways can the product be fully parenthesized?
- 42
- 24
- 14
- 5
Show the answer
C. 14
A product of factors has full parenthesizations: the last multiplication splits it into two smaller products. With five factors, .
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?
- 81
- 24
- 21
- 27
Show the answer
B. 24
Burnside's lemma averages the fixed colorings over the 4 rotations: the identity fixes , the half-turn , the two quarter-turns each. .
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).