Module contents
Lesson 10 of 22Review 110 min

Counting: rules, binomial coefficients, pigeonhole and inclusion-exclusion

A rigorous review of counting: sum and product rules, bijections, ordered selections, permutations and combinations with and without repetition, stars and bars, the binomial theorem, double counting, pigeonhole and inclusion–exclusion. Each formula is checked against explicit enumeration.

After this lesson you can

  • Choose the correct counting model for order, repetition and distinguishability and justify it by a bijection
  • Prove binomial identities by double counting as well as algebra
  • Apply the pigeonhole principle, including its generalized form, and prove R(3, 3) = 6
  • Count derangements and surjections using inclusion–exclusion
  • Implement enumerators and check formulas by brute force with exact integers

Before you start

Motivation: count before enumerating

Before writing an exhaustive search, take ten seconds to count: how many cases? The answer determines feasibility or whether another approach is needed.

  • Hyperparameter grids. Five hyperparameters with ten values each give 10510^5 configurations. At one minute per training run, that is over two months of compute. This is the product rule, and why random or Bayesian search replaces grids beyond two or three axes.
  • Feature selection. With d=40d = 40 features there are 240≈1.1×10122^{40} \approx 1.1\times 10^{12} subsets. Evaluating a model per subset is impossible, hence greedy methods and ℓ1\ell_1 regularization.
  • Routes. A traveling salesperson visiting 20 cities and returning to the origin has 19!/2≈6.1×101619!/2 \approx 6.1\times 10^{16} distinct tours. Even at a billion per second it takes more than a year.
  • Token sequences. With GPT-2’s 50,257-token vocabulary and a context of 1024 positions, there are 502571024≈10481450257^{1024} \approx 10^{4814} possible sequences. A language model cannot memorize that space: it must generalize.
  • Hypotheses. On 6 input bits there are 226=264≈1.8×10192^{2^6} = 2^{64} \approx 1.8\times 10^{19} Boolean functions. Counting how many a model family can express is precisely the growth function; its bound, the Sauer–Shelah lemma, is a counting argument like those here.
  • Games. Go has about 2.08×101702.08\times 10^{170} legal positions on a 19×1919\times 19 board (Tromp, 2016). AlphaZero therefore does not explore the entire game tree: it samples a tiny part guided by a network.

These figures follow from a handful of principles: add disjoint cases, multiply successive choices, find a bijection with something countable, divide when each object is counted repeatedly, and correct overlapping cases with alternating signs. This lesson densely reviews these principles with full proofs and the habit preventing most mistakes: check every counting formula against explicit enumeration in small cases. Finite sums recur in the hypergeometric distribution, recurrences and generating functions.

Basic rules

Everything rests on four facts about finite sets. Recall ∣A∣=n\abs{A} = n means a bijection between AA and {1,…,n}\{1, \dots, n\} (lesson 3’s cardinality).

Proof

The sum rule for two disjoint sets concatenates bijections A→{1,…,a}A \to \{1, \dots, a\} and B→{a+1,…,a+b}B \to \{a + 1, \dots, a + b\}; for mm sets use induction on mm. The sequential product form also follows by induction on mm: group objects by first choice. There are n1n_1 disjoint groups and, by induction on the remaining m−1m - 1 choices, each has n2⋯nmn_2\cdots n_m objects; the sum rule gives n1⋅n2⋯nmn_1 \cdot n_2\cdots n_m. The bijection rule is the definition of cardinality. The quotient rule applies the sum rule to the partition of AA into ∣B∣\abs{B} disjoint fibers, each of size dd.

∎

The sequential product form has a subtlety: the number of options at each step must be constant, not the set. Arranging nn people in a line, the second position can hold anyone except the first chosen. The candidate set depends on the prior choice, but its size is always n−1n - 1, sufficient for n(n−1)⋯1=n!n(n-1)\cdots 1 = n!.

A decision tree depicts the product rule: root “nothing chosen yet,” each level a choice, each leaf a complete sequence. If each level-ii node has nin_i children, there are n1⋯nmn_1\cdots n_m leaves.

InteractiveA counting decision tree
startaabcdbabcdcabcddabcdchoice 1 · 4 brancheschoice 2 · 3 brancheschoice 3 · 2 branches
  • allowed sequence
  • repeated branch (discarded)
  • selected sequence
Available symbols nn
Choices kk
Build the tree level by level
level 3 of 3
orderedunorderedno repetition
nk‾n^{\underline{k}}
24
(nk)\binom{n}{k}
4
repetition
nkn^k
64
(n+k−1k)\binom{n+k-1}{k}
20
Tree leaves (sequences)4 · 3 · 2 = 24
Each leaf is a sequence of kk choices from nn symbols. Start with order and no repetition: branches repeating a symbol turn off, leaving 4⋅3⋅2=244 \cdot 3 \cdot 2 = 24 leaves. Disable ‘Order matters’: leaves group into classes, one per selection, and the increasing branch (orange) represents each; all classes have 3!=63! = 6 leaves. Now enable repetition: do all still have the same size? See what dividing leaves by k!k! gives and compare the table.

Ordering and choosing: four situations

Choosing kk objects from nn has four interpretations according to whether selection order matters and whether an object may be selected repeatedly. The figure covers all four; now formalize them.

Proof

Both sequence counts use the product rule: with repetition there are nn choices at each of kk selections; without repetition, n−i+1n - i + 1 at choice ii, regardless of previous choices. For combinations without repetition, map each kk-permutation to its element set. This is surjective and each size-kk subset is the image of exactly its k!k! orderings, so the quotient rule gives nk‾=k!(nk)n^{\underline{k}} = k!\binom{n}{k}. Combinations with repetition are counted next using stars and bars.

∎

The figure tests the quotient rule. Without repetition each class has exactly k!k! leaves, because kk distinct symbols have k!k! orderings. With repetition, no: multiset {a,a,a}\{a, a, a\} has one ordering, {a,a,b}\{a, a, b\} three and {a,b,c}\{a, b, c\} six. Fibers have different sizes, the quotient rule does not apply and nk/k!n^k/k! is not even an integer: n=4n = 4 and k=3k = 3 give 64/6≈10.6764/6 \approx 10.67, versus answer (63)=20\binom{6}{3} = 20. The figure also shows choosing a canonical representative per class, the increasing sequence (a≤b≤ca \le b \le c with repetition, a<b<ca < b < c without), and counting only those branches.

Words with repeated letters: multinomial coefficients

How many distinct words rearrange MISSISSIPPI? If all 11 letters were distinguishable (add subscripts S1,S2,…S_1, S_2, \dots) there would be 11!11! orderings. Removing subscripts, each word corresponds to exactly 1! 4! 4! 2!1!\,4!\,4!\,2! subscripted orderings (the M, four I’s, four S’s and two P’s among themselves), so the quotient rule gives

(111,4,4,2)=11!1! 4! 4! 2!=34 650.\binom{11}{1, 4, 4, 2} = \frac{11!}{1!\,4!\,4!\,2!} = 34\,650.

Generally the multinomial coefficient (nk1,…,km)=n!k1!⋯km!\binom{n}{k_1, \dots, k_m} = \frac{n!}{k_1!\cdots k_m!} with k1+⋯+km=nk_1 + \cdots + k_m = n counts length-nn words with kik_i copies of symbol ii, or equivalently distributions of nn distinguishable objects into mm labeled boxes with kik_i objects in box ii. It also follows by choosing each symbol’s positions successively: (nk1)(n−k1k2)⋯\binom{n}{k_1}\binom{n - k_1}{k_2}\cdots, a product telescoping to the same fraction. The binomial is m=2m = 2: (nk)=(nk, n−k)\binom{n}{k} = \binom{n}{k,\, n-k}.

Balls into boxes

Many problems become distributing kk balls among nn boxes, i.e. functions from a kk-element set to an nn-element set. Stanley’s twelvefold way organizes cases by whether balls and boxes are distinguishable and whether the function is arbitrary, injective or surjective. With distinguishable boxes six cases remain, five already known:

kk balls in nn boxesarbitraryinjective (at most one per box)surjective (no empty box)
distinguishable ballsnkn^knk‾n^{\underline{k}}∑j(−1)j(nj)(n−j)k\sum_{j}(-1)^j\binom{n}{j}(n-j)^k
indistinguishable balls(n+k−1k)\binom{n+k-1}{k}(nk)\binom{n}{k}(k−1n−1)\binom{k-1}{n-1}

The surjection entry for distinguishable balls is proved using inclusion–exclusion at the end. Indistinguishable boxes yield Stirling numbers of the second kind, expressible only as an alternating sum (seen later), and integer partitions without a closed formula; see Stirling and Bell numbers.

Stars and bars

A size-kk combination with repetition on {1,…,n}\{1, \dots, n\} is determined by each element’s multiplicity: xi≥0x_i \ge 0 copies of element ii, with x1+⋯+xn=kx_1 + \cdots + x_n = k. Thus counting multisets counts nonnegative integer solutions of a linear equation, for which there is a useful bijection.

Proof

Write a solution as a string of nn stars and k−1k - 1 bars: x1x_1 stars, a bar, x2x_2 stars, a bar, and so on through xkx_k stars. For example (2,0,3,2)(2, 0, 3, 2) with n=7n = 7 is ⋆⋆ ∣ ∣ ⋆⋆⋆ ∣ ⋆⋆\star\star\,|\,|\,\star\star\star\,|\,\star\star. This bijects solutions with length-n+k−1n + k - 1 strings containing exactly k−1k - 1 bars: the inverse counts stars between successive bars (and before the first and after the last). Such a string is determined by its bar positions, a size-k−1k - 1 subset of {1,…,n+k−1}\{1, \dots, n + k - 1\}. The bijection rule gives (n+k−1k−1)\binom{n+k-1}{k-1} solutions.

For xi≥1x_i \ge 1, substitution yi=xi−1y_i = x_i - 1 bijects with solutions of y1+⋯+yk=n−ky_1 + \cdots + y_k = n - k, yi≥0y_i \ge 0, of which there are (n−k+k−1k−1)=(n−1k−1)\binom{n - k + k - 1}{k - 1} = \binom{n-1}{k-1}. Visually reserve a star for each box and distribute the rest; or place the k−1k - 1 bars in k−1k - 1 of the n−1n - 1 gaps between stars, without repeating gaps.

∎

Feller popularized the bijection and name stars and bars in his probability book. It completes the missing table entry: a size-kk multiset on nn elements solves x1+⋯+xn=kx_1 + \cdots + x_n = k, giving (k+n−1k)\binom{k + n - 1}{k}.

InteractiveDraggable stars and bars
stars and barspositions (1 = bar)010203040506071819110x1 = 7x2 = 0x3 = 0x4 = 0
7
Boxes kk
Constraint
Traverse all configurations
1 of 120
Solution7+0+0+0=77 + 0 + 0 + 0 = 7
Bars at{8,9,10}⊆{1,…,10}\{8, 9, 10\} \subseteq \{1, \dots, 10\}
Configurations, (n+k−1k−1)\binom{n+k-1}{k-1}(103)=120\binom{10}{3} = 120
Two adjacent bars, or one at an edge, leave an empty box: 3 variables are zero.
Drag any bar: the stars-and-bars string, binary position word and boxes are three encodings of one solution. Join two bars to empty a box and move one to an end. Play the counter to traverse the (103)=120\binom{10}{3} = 120 configurations in order and check none repeats. Switch to xi≥1x_i \ge 1: hollow stars are reserved and the count becomes (n−1k−1)\binom{n-1}{k-1}.

Three variants reduce to the same bijection:

  • Lower bounds. x1+x2+x3+x4=10x_1 + x_2 + x_3 + x_4 = 10 with x1≥2x_1 \ge 2: set x1′=x1−2x_1' = x_1 - 2 and count nonnegative solutions of sum 8, (113)=165\binom{11}{3} = 165.
  • Inequalities. Solutions of x1+⋯+xk≤nx_1 + \cdots + x_k \le n with xi≥0x_i \ge 0 are solutions of x1+⋯+xk+s=nx_1 + \cdots + x_k + s = n with slack variable s≥0s \ge 0: (n+kk)\binom{n + k}{k}.
  • Monomials. A degree-dd monomial in mm variables, z1a1⋯zmamz_1^{a_1}\cdots z_m^{a_m} with ∑ai=d\sum a_i = d, solves a stars-and-bars equation: there are (d+m−1m−1)\binom{d + m - 1}{m - 1}. Those of degree ≤d\le d number (m+dd)\binom{m + d}{d} by the previous variant. A degree-3 polynomial feature expander over 100 variables (like scikit-learn’s PolynomialFeatures(degree=3), constant included) produces (1033)=176 851\binom{103}{3} = 176\,851 columns: monomials grow like d m/m!d^{\,m}/m! for fixed mm and like md/d!m^d/d! for fixed dd, so kernel methods compute inner products in that space without constructing it.

Upper bounds (xi≤cx_i \le c) do not reduce by substitution. They require inclusion–exclusion, covered at the end.

Binomial theorem and Pascal’s triangle

Proof

Combinatorial proof. Expand (x+y)(x+y)⋯(x+y)(x + y)(x + y)\cdots(x + y) distributively without commuting: obtain 2n2^n length-nn words in xx and yy, one per choice of a letter from each factor. After commuting, each word with kk letters xx becomes xkyn−kx^k y^{n-k}, and there are as many as size-kk subsets of the nn factors (positions of xx): (nk)\binom{n}{k}.

Inductive proof. For n=0n = 0 both sides are 1. Assuming nn, multiply by (x+y)(x + y) and collect the coefficient of xkyn+1−kx^k y^{n+1-k}: (nk−1)+(nk)\binom{n}{k-1} + \binom{n}{k}, or (n+1k)\binom{n+1}{k} by Pascal’s rule below. At k=0k = 0 and k=n+1k = n + 1 one term is zero and the other 1, as is (n+1k)\binom{n+1}{k}.

∎

Commutativity matters. For matrices, (A+B)2=A2+AB+BA+B2(\mat{A} + \mat{B})^2 = \mat{A}^2 + \mat{A}\mat{B} + \mat{B}\mat{A} + \mat{B}^2, and only when AB=BA\mat{A}\mat{B} = \mat{B}\mat{A} can cross terms combine into 2AB2\mat{A}\mat{B}. The combinatorial proof explains this: count words after commuting. Thus eA+B=eAeBe^{\mat{A} + \mat{B}} = e^{\mat{A}}e^{\mat{B}} holds for commuting matrices and fails generally otherwise. The same argument gives the multinomial theorem:

(x1+⋯+xm)n=∑k1+⋯+km=n(nk1,…,km)x1k1⋯xmkm,(x_1 + \cdots + x_m)^n = \sum_{k_1 + \cdots + k_m = n} \binom{n}{k_1, \dots, k_m} x_1^{k_1}\cdots x_m^{k_m},

with (n+m−1m−1)\binom{n + m - 1}{m - 1} terms, one per stars-and-bars solution. The fact that the binomial formula holds for all nn and coefficients count subsets is the binomial theorem; substituting values gives identities:

  • x=y=1x = y = 1: ∑k(nk)=2n\sum_k \binom{n}{k} = 2^n. Subsets of all sizes are all subsets.
  • x=−1x = -1, y=1y = 1, n≥1n \ge 1: ∑k(−1)k(nk)=0\sum_k (-1)^k\binom{n}{k} = 0. A nonempty set has equally many even- and odd-size subsets (bijection: add or remove a fixed element).
  • Differentiate with respect to xx and evaluate at x=y=1x = y = 1: ∑kk(nk)=n2n−1\sum_k k\binom{n}{k} = n2^{n-1}.
Proof

Fix element aa of an nn-element set. Size-kk subsets split into those containing aa (choose the other k−1k - 1 among n−1n - 1) and those not containing it (choose kk among n−1n - 1): sum rule. Symmetry is the bijection S↦A∖SS \mapsto A \setminus S between subsets of size kk and n−kn - k, the complement.

∎

Placing (nk)\binom{n}{k} in row nn, position kk, yields Pascal’s triangle, with each number the sum of the two above. Its diagonals, rows and row combinations encode many identities.

InteractiveIdentities in Pascal's triangle
11112113311464115101051161520156117213535217118285670562881193684126126843691110451202102522101204510111155165330462462330165551111126622049579292479249522066121
∑i=27(i2)=1+3+6+10+15+21=56=(83)\sum_{i=2}^{7} \binom{i}{2} = 1 + 3 + 6 + 10 + 15 + 21 = 56 = \binom{8}{3}
Hockey-stick identity: ∑i=rn(ir)=(n+1r+1)\sum_{i=r}^{n} \binom{i}{r} = \binom{n+1}{r+1}
  • terms
  • result
Terms6
A subset of size 33 of {1,…,8}\{1, \dots, 8\} is determined by its largest element jj and the remaining 22 elements chosen from {1,…,j−1}\{1, \dots, j - 1\}: one term per jj.
Choose an identity and hover over (or click) cells. Start with the hockey stick: the magenta cell is the sum of the blue diagonal ending just above and left. In ‘Vandermonde’ the selected cell combines two rows whose sizes sum to its row; move mm and watch products change but not the total. Finish with ‘Modulo pp’: coloring by remainder reveals the Sierpinski triangle. Readouts check Lucas's theorem at the selected cell.
Proof

For hockey stick, classify size-r+1r + 1 subsets of {1,…,n+1}\{1, \dots, n + 1\} by largest element jj. With largest jj, the other rr elements are chosen from {1,…,j−1}\{1, \dots, j - 1\} in (j−1r)\binom{j - 1}{r} ways. Sum over j=r+1,…,n+1j = r + 1, \dots, n + 1 and index by i=j−1i = j - 1. You will prove Vandermonde similarly in exercises.

∎

The triangle modulo p: Lucas’s theorem

In the figure’s “modulo pp” mode, cells divisible by pp form nested triangular gaps. This is not a visual coincidence: parity of (nk)\binom{n}{k} can be read from bits of nn and kk.

Proof

First (pj)=p!j! (p−j)!\binom{p}{j} = \frac{p!}{j!\,(p-j)!} is divisible by pp for 0<j<p0 < j < p: prime pp divides the numerator and no denominator factor. By the binomial theorem, (1+x)p≡1+xp(1 + x)^p \equiv 1 + x^p as polynomials modulo pp, and by induction (1+x)pi≡1+xpi(1 + x)^{p^i} \equiv 1 + x^{p^i}. Then

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

Expanding the right product, each term has exponent ∑ijipi\sum_i j_i p^i with 0≤ji≤ni<p0 \le j_i \le n_i < p. Uniqueness of base-pp representation makes the only term with exponent kk that with ji=kij_i = k_i for every ii (there is none if some ki>nik_i > n_i, in which case (niki)=0\binom{n_i}{k_i} = 0). Equating coefficients of xkx^k proves the theorem.

∎

The binary corollary counts odd entries in each row: there are as many kk with bits contained in those of nn as subsets of the 1-bit set of nn, namely 2s(n)2^{s(n)} if nn has s(n)s(n) binary ones. Row 21 =(10101)2= (10101)_2 has 23=82^3 = 8 odd entries, and in the figure (216)=54 264\binom{21}{6} = 54\,264 is even because the bit of weight 2 in 6=(110)26 = (110)_2 is absent from 21. Rows 2j−12^j - 1, all ones, are entirely odd; rows 2j2^j have odd entries only at the ends, where each new fractal gap starts.

Double counting

An identity between numeric expressions can be proved algebraically, but a technique also explains why: find a set counted by both expressions.

Double counting is also the finite form of Fubini’s theorem (exchanging double-sum order), behind nontrivial proofs such as Pitman’s proof of Cayley’s labeled-tree formula and the Kővári–Sós–Turán extremal-graph bound. When an identity has binomial coefficients, seek the set before induction.

The pigeonhole principle

Proof

The first is the case ⌈∣A∣/∣B∣⌉≥2\lceil \abs{A}/\abs{B}\rceil \ge 2 of the second. For the second, suppose otherwise: if every fiber had at most ⌈∣A∣/∣B∣⌉−1\lceil \abs{A}/\abs{B}\rceil - 1 elements, since fibers partition AA, we would have ∣A∣≤∣B∣(⌈∣A∣/∣B∣⌉−1)<∣B∣⋅∣A∣∣B∣=∣A∣\abs{A} \le \abs{B}\left(\lceil \abs{A}/\abs{B}\rceil - 1\right) < \abs{B}\cdot\frac{\abs{A}}{\abs{B}} = \abs{A}, because ⌈t⌉−1<t\lceil t \rceil - 1 < t. Contradiction.

∎

The pigeonhole principle is the contrapositive of an obvious claim about injective functions, but its strength lies in choosing pigeons and holes well. It is a nonconstructive existence argument: it guarantees a collision without locating it.

  • No universal compressor. No lossless compression algorithm shortens every nn-bit string: there are 2n2^n length-nn strings and only 2n−12^n - 1 shorter strings (including empty). If it compresses one, it lengthens another. This is the combinatorial version of the source coding theorem limits.
  • Every hash has collisions. A 256-bit hash applied to 2256+12^{256} + 1 distinct inputs gives two equal outputs. Cryptographic hash security does not mean collisions do not exist, but that finding them is infeasible. The birthday paradox, seen in probability, says roughly 21282^{128} trials suffice to expect one, not 22562^{256}: hash lengths use twice the bits of desired security.
  • Divisible sums. Among any nn integers a1,…,ana_1, \dots, a_n is a nonempty consecutive block whose sum is divisible by nn. Pigeons are n+1n + 1 partial sums s0=0,s1,…,sns_0 = 0, s_1, \dots, s_n; holes are nn remainders modulo nn. Two coincide, si≡sjs_i \equiv s_j with i<ji < j, so nn divides ai+1+⋯+aja_{i+1} + \cdots + a_j.
Proof

Let a1,…,an2+1a_1, \dots, a_{n^2+1} be the sequence. Assign each position ii the pair (ci,di)(c_i, d_i): the lengths of the longest increasing subsequence ending at aia_i and the longest decreasing subsequence ending at aia_i. Suppose both lengths are always ≤n\le n. Then there are at most n2n^2 possible pairs and n2+1n^2 + 1 positions: by pigeonhole, two positions i<ji < j have the same pair. But if ai<aja_i < a_j, appending aja_j to the longest increasing subsequence ending at aia_i gives cj≥ci+1c_j \ge c_i + 1; if ai>aja_i > a_j, similarly dj≥di+1d_j \ge d_i + 1. Either way pairs differ. Contradiction.

∎

The bound is tight: 3,2,1,6,5,4,9,8,73, 2, 1, 6, 5, 4, 9, 8, 7 has n2=9n^2 = 9 elements and no monotone subsequence of length 4. The proof does not search for the subsequence; labels (ci,di)(c_i, d_i) can however be calculated by O(N2)\bigO(N^2) dynamic programming that does find it.

First encounter with Ramsey: R(3, 3) = 6

In any six-person group, three mutually know one another or three are mutual strangers. Graphically, color each edge of complete graph K6K_6 red or blue; a triangle with all edges one color always exists.

Proof

Take a vertex vv of K6K_6. It has 5 edges and 2 colors, so generalized pigeonhole gives at least ⌈5/2⌉=3\lceil 5/2 \rceil = 3 of one color, say red, to vertices a,b,ca, b, c. If any of abab, acac, bcbc is red, it forms a red triangle with vv. Otherwise all three are blue and abcabc is blue.

For K5K_5, arrange vertices in a pentagon, coloring sides red and diagonals blue. Each color forms a 5-cycle, which has no triangles.

∎
InteractiveTry to avoid the monochromatic triangle
123456
  • red
  • blue
  • uncolored
  • monochromatic triangle (shaded)
Complete graph
Colored edges10 of 15
Monochromatic triangles0
Blocked edges0
Color the 5 edges of vertex 6 (5 remaining).
K6K_6 starts as a red pentagon with its blue pentagram and a central vertex with uncolored edges: that K5K_5 has no monochromatic triangles. Click edges of vertex 6 to color them and try not to complete a triangle. Thick-shadow edges already have no escape. The pigeonhole argument starts at the marked vertex: click another to change it. Try ‘Random’ several times and note the smallest triangle count. Then switch to K5K_5 and find a triangle-free coloring yourself.

The central vertex is the entire argument: at least 3 of its 5 edges share a color, and any 3 pentagon vertices have at least one pentagon side (red) and one diagonal (blue), because a 5-cycle has neither 3 pairwise nonadjacent vertices (giving the side) nor 3 pairwise adjacent vertices (giving the diagonal). If the center’s 3 edges are red, the side closes a red triangle; if blue, the diagonal closes a blue one. Enumerating the 215=32 7682^{15} = 32\,768 colorings below confirms more: every K6K_6 coloring has at least two monochromatic triangles (Goodman, 1959), and K5K_5 has exactly 12 colorings without them, the 12 Hamiltonian cycles of K5K_5 (each with its complement).

Ramsey number R(s,t)R(s, t) is the smallest NN such that every red-blue coloring of KNK_N contains a red KsK_s or blue KtK_t. You proved R(3,3)=6R(3, 3) = 6. It is known R(4,4)=18R(4, 4) = 18, while R(5,5)R(5, 5) is known only to lie between 43 and 46 (upper bound Angeltveit and McKay, 2024). Ramsey numbers return with more tools, and Erdős’s exponential lower bound R(k,k)>2k/2R(k, k) > 2^{k/2} for k≥3k \ge 3 is a founding example of the probabilistic method: a counting argument proving a good coloring exists without constructing it.

Inclusion–exclusion

The sum rule requires disjoint sets. If they overlap, ∣A∣+∣B∣\abs{A} + \abs{B} counts A∩BA \cap B twice, and ∣A∪B∣=∣A∣+∣B∣−∣A∩B∣\abs{A \cup B} = \abs{A} + \abs{B} - \abs{A \cap B}. For three sets subtract all three pairwise overlaps and add the triple intersection back, having subtracted it once too often. The general pattern alternates signs.

Proof

Check each x∈Ux \in U‘s contribution to the second formula’s right side (the first follows by subtracting from ∣U∣\abs{U}). Let T={i:x∈Ai}T = \{i : x \in A_i\} and t=∣T∣t = \abs{T}. Element xx is in AIA_I exactly when I⊆TI \subseteq T, so contributes

∑I⊆T(−1)∣I∣=∑j=0t(−1)j(tj)=(1−1)t={1if t=0,0if t≥1,\sum_{I \subseteq T} (-1)^{\abs{I}} = \sum_{j=0}^{t} (-1)^j \binom{t}{j} = (1 - 1)^t = \begin{cases} 1 & \text{if } t = 0, \\ 0 & \text{if } t \ge 1, \end{cases}

by the binomial theorem. Thus the right side counts exactly elements in no AiA_i.

∎

The inclusion–exclusion principle usually appears in symmetric form: if ∣AI∣\abs{A_I} depends only on j=∣I∣j = \abs{I}, say ∣AI∣=Nj\abs{A_I} = N_j, the (mj)\binom{m}{j} intersections of size jj contribute equally and

∣U∖(A1∪⋯∪Am)∣=∑j=0m(−1)j(mj)Nj.\abs{U \setminus (A_1 \cup \cdots \cup A_m)} = \sum_{j=0}^{m} (-1)^j \binom{m}{j} N_j.

The recipe is always: define “bad properties” AiA_i, count what happens imposing jj simultaneously, and alternate signs. Three classic examples follow.

Derangements

A derangement of {1,…,n}\{1, \dots, n\} is a permutation σ\sigma with no fixed points: σ(i)≠i\sigma(i) \neq i for all ii. The hat problem: nn people leave hats at a cloakroom and receive them back randomly; how many ways give nobody their own?

Let AiA_i be permutations fixing ii. Imposing jj specific fixed points leaves n−jn - j elements to permute freely: Nj=(n−j)!N_j = (n - j)!. By symmetric inclusion–exclusion,

Dn=∑j=0n(−1)j(nj)(n−j)!=n!∑j=0n(−1)jj!.D_n = \sum_{j=0}^{n}(-1)^j\binom{n}{j}(n - j)! = n!\sum_{j=0}^{n}\frac{(-1)^j}{j!}.

This is the truncated Taylor series for e−1e^{-1}. The fraction of permutations without fixed points approaches 1/e≈0.36791/e \approx 0.3679 rapidly: alternating-series error is bounded by the first omitted term, so ∣Dn−n!/e∣<n!/(n+1)!=1/(n+1)≤1/2\abs{D_n - n!/e} < n!/(n+1)! = 1/(n + 1) \le 1/2 for n≥1n \ge 1, and DnD_n is the nearest integer to n!/en!/e. First values are 1,0,1,2,9,44,265,18541, 0, 1, 2, 9, 44, 265, 1854 (for n=0,…,7n = 0, \dots, 7).

There is also Dn=(n−1)(Dn−1+Dn−2)D_n = (n - 1)(D_{n-1} + D_{n-2}) for n≥2n \ge 2, with a short combinatorial proof. In a derangement, nn goes to some i≠ni \neq n (n−1n - 1 choices). If ii goes to nn, they swap and the rest is a derangement of n−2n - 2 elements. Otherwise “merge” ii with nn (forbid ii going to nn as previously forbidden from itself), giving a derangement of n−1n - 1 elements. Derangements return as permutations without length-1 cycles in cycle decomposition.

Surjections

How many surjections are there from an nn-element set to a kk-element one? Let AiA_i be functions not taking value ii. Forbidding jj specific values leaves (k−j)n(k - j)^n functions:

Sobre⁡(n,k)=∑j=0k(−1)j(kj)(k−j)n.\operatorname{Sobre}(n, k) = \sum_{j=0}^{k}(-1)^j\binom{k}{j}(k - j)^n.

For example Sobre⁡(4,3)=81−3⋅16+3⋅1−0=36\operatorname{Sobre}(4, 3) = 81 - 3\cdot 16 + 3\cdot 1 - 0 = 36: surjections from 4 to 3 choose the pair sharing an image ((42)=6\binom{4}{2} = 6), then a bijection from 3 blocks to 3 values (3!=63! = 6). Dividing by k!k! gives Stirling numbers of the second kind, S(n,k)=Sobre⁡(n,k)/k!S(n, k) = \operatorname{Sobre}(n, k)/k!, counting partitions into kk nonempty blocks. The alternating sum contains huge powers (k−j)n(k - j)^n that nearly cancel, so only exact integers can calculate it reliably; the coding exercise checks this.

Euler’s φ function

φ(n)\varphi(n) counts integers in {1,…,n}\{1, \dots, n\} coprime to nn. If primes dividing nn are p1,…,prp_1, \dots, p_r, let AiA_i be multiples of pip_i in {1,…,n}\{1, \dots, n\}. Common multiples of primes indexed by II are multiples of their product, so ∣AI∣=n/∏i∈Ipi\abs{A_I} = n/\prod_{i \in I}p_i and

φ(n)=∑I(−1)∣I∣n∏i∈Ipi=n∏i=1r(1−1pi),\varphi(n) = \sum_{I}(-1)^{\abs{I}}\frac{n}{\prod_{i\in I}p_i} = n\prod_{i=1}^{r}\left(1 - \frac{1}{p_i}\right),

where the last equality expands the product. For n=360=23⋅32⋅5n = 360 = 2^3\cdot 3^2\cdot 5: φ(360)=360⋅12⋅23⋅45=96\varphi(360) = 360\cdot\frac12\cdot\frac23\cdot\frac45 = 96. Function φ\varphi is central to modular congruence arithmetic.

Upper bounds in stars and bars

How many solutions of x1+x2+x3+x4=12x_1 + x_2 + x_3 + x_4 = 12 have 0≤xi≤50 \le x_i \le 5? Let AiA_i be nonnegative solutions with xi≥6x_i \ge 6. Imposing jj such bounds subtracts 6j6j from the total (the stars-and-bars substitution), so Nj=(12−6j+33)N_j = \binom{12 - 6j + 3}{3} while 12−6j≥012 - 6j \ge 0:

(153)−(41)(93)+(42)(33)=455−336+6=125.\binom{15}{3} - \binom{4}{1}\binom{9}{3} + \binom{4}{2}\binom{3}{3} = 455 - 336 + 6 = 125.

Truncating the sum: Bonferroni

Truncating inclusion–exclusion does not give arbitrary values: partial sums alternate upper and lower bounds. With Sj=∑∣I∣=j∣AI∣S_j = \sum_{\abs{I} = j}\abs{A_I},

∣⋃iAi∣≤S1,∣⋃iAi∣≥S1−S2,∣⋃iAi∣≤S1−S2+S3,…\abs{\textstyle\bigcup_i A_i} \le S_1, \qquad \abs{\textstyle\bigcup_i A_i} \ge S_1 - S_2, \qquad \abs{\textstyle\bigcup_i A_i} \le S_1 - S_2 + S_3, \quad \dots

The first is the union bound, the most-used inequality in learning theory (turning a guarantee for one hypothesis into a simultaneous guarantee for a finite family). The rest are Bonferroni inequalities.

Implementation from scratch

First, lazy generators (Python generators) for three of four families (the fourth, sequences with repetition, is a Cartesian product: itertools.product) and stars-and-bars solutions. Their structure proves their formulas: combinations follow Pascal’s rule (with or without the first element) and kk-permutations the product rule. Then compare against formulas and itertools.

[ ]Generators from scratch and verificationBrowser
from math import comb, perm, factorial
import itertools

def k_permutaciones(items, k):
    """Secuencias de k elementos distintos, en orden lexicográfico."""
    if k == 0:
        yield ()
        return
    for i, x in enumerate(items):
        resto = items[:i] + items[i + 1:]
        for cola in k_permutaciones(resto, k - 1):      # regla del producto
            yield (x,) + cola

def combinaciones(items, k):
    """Subconjuntos de tamaño k (como tuplas crecientes)."""
    if k == 0:
        yield ()
        return
    if len(items) < k:
        return
    primero, resto = items[0], items[1:]
    for cola in combinaciones(resto, k - 1):            # las que contienen al primero
        yield (primero,) + cola
    yield from combinaciones(resto, k)                  # las que no: regla de Pascal

def multicombinaciones(items, k):
    """Multiconjuntos de tamaño k (tuplas no decrecientes)."""
    if k == 0:
        yield ()
        return
    if not items:
        return
    primero = items[0]
    for cola in multicombinaciones(items, k - 1):       # usar el primero (otra vez)
        yield (primero,) + cola
    yield from multicombinaciones(items[1:], k)         # no volver a usarlo

def composiciones(n, k):
    """Soluciones de x1 + ... + xk = n con xi >= 0."""
    if k == 1:
        yield (n,)
        return
    for x in range(n + 1):
        for resto in composiciones(n - x, k - 1):
            yield (x,) + resto

def barras(x):
    """Estrellas y barras: posiciones (desde 0) de las barras en la cadena."""
    pos, i = [], 0
    for xi in x[:-1]:
        i += xi
        pos.append(i)
        i += 1
    return tuple(pos)

contar = lambda gen: sum(1 for _ in gen)
multi = lambda n, k: comb(n + k - 1, k) if n + k > 0 else 1   # el multiconjunto vacío de un conjunto vacío
casos = 0
for n in range(0, 8):
    items = tuple(range(n))
    for k in range(0, n + 2):
        assert contar(k_permutaciones(items, k)) == perm(n, k)
        assert contar(combinaciones(items, k)) == comb(n, k)
        assert contar(multicombinaciones(items, k)) == multi(n, k)
        # mismo orden que itertools
        assert list(k_permutaciones(items, k)) == list(itertools.permutations(items, k))
        assert list(combinaciones(items, k)) == list(itertools.combinations(items, k))
        assert list(multicombinaciones(items, k)) == list(itertools.combinations_with_replacement(items, k))
        casos += 1
    for k in range(1, 6):
        sols = list(composiciones(n, k))
        assert len(sols) == comb(n + k - 1, k - 1)
        # la codificación con barras es una biyección sobre los (k-1)-subconjuntos de n+k-1 posiciones
        assert sorted(map(barras, sols)) == list(itertools.combinations(range(n + k - 1), k - 1))
        casos += 1
print("casos comprobados:", casos, "  todos coinciden con las fórmulas y con itertools")
print("ejemplo, (2, 0, 3, 2) ->", barras((2, 0, 3, 2)), " (cadena ★★||★★★|★★)")
print("MISSISSIPPI:", factorial(11) // (factorial(4) ** 2 * factorial(2)),
      "  palabras distintas por fuerza bruta:", len(set(itertools.permutations("MISSISP"))),
      "de", factorial(7), "ordenaciones de MISSISP")

The final line checks the quotient rule with shorter MISSISP (one M, two I’s, three S’s, one P), making brute force instant: its 7!=50407! = 5040 orderings yield 7!1! 2! 3! 1!=420\frac{7!}{1!\,2!\,3!\,1!} = 420 distinct words, each repeated 2! 3!=122!\,3! = 12 times.

Now derangements three ways: inclusion–exclusion with exact integers, recurrence, and brute force. Finally the mathematically correct “nearest integer to n!/en!/e” formula evaluated in floating point.

[ ]Derangements three waysBrowser
from math import comb, factorial, e
from itertools import permutations

def desarreglos_ie(n):
    return sum((-1) ** j * comb(n, j) * factorial(n - j) for j in range(n + 1))

def desarreglos_rec(n):
    if n == 0:
        return 1
    a, b = 1, 0                                  # D_0, D_1
    for m in range(2, n + 1):
        a, b = b, (m - 1) * (a + b)
    return b

def desarreglos_fb(n):
    return sum(all(p[i] != i for i in range(n)) for p in permutations(range(n)))

print(" n   IE      recurrencia  fuerza bruta   D_n / n!")
for n in range(9):
    ie, rec, fb = desarreglos_ie(n), desarreglos_rec(n), desarreglos_fb(n)
    assert ie == rec == fb
    print(f"{n:2d}  {ie:6d}  {rec:8d}  {fb:10d}       {ie / factorial(n):.6f}")
print("1/e =", round(1 / e, 6))

assert all(desarreglos_ie(n) == desarreglos_rec(n) for n in range(60))
fallo = next(n for n in range(1, 60) if round(factorial(n) / e) != desarreglos_rec(n))
print(f"\nround(n!/e) en coma flotante falla por primera vez en n = {fallo}:")
print("  float:", round(factorial(fallo) / e), "  exacto:", desarreglos_rec(fallo))

The table confirms all three and convergence to 1/e1/e: at n=8n = 8 the fraction differs from 1/e1/e by 2.5×10−62.5\times 10^{-6}, below the first-omitted-term bound 1/9!≈2.8×10−61/9! \approx 2.8\times 10^{-6}. The last line is the warning: “nearest integer to n!/en!/e” is exact over reals, but floating-point operations can have relative error up to 2−532^{-53}, and once n!/en!/e exceeds 252≈4.5×10152^{52} \approx 4.5\times 10^{15} that error can exceed half a unit. This first occurs at n=19n = 19, with 19!/e≈4.5×101619!/e \approx 4.5\times 10^{16}: rounding is off by 6.

Now pigeonhole and Ramsey by brute force. Each KnK_n coloring is a bit mask (bit ee = edge ee‘s color) and each triangle its three-edge mask: monochromatic if the coloring has all three bits 0 or all 1. We also check Erdős–Szekeres on random permutations.

[ ]R(3, 3) = 6 and Erdős–Szekeres by brute forceBrowser
from itertools import combinations
from collections import Counter
import random

def triangulos_mono(n):
    aristas = list(combinations(range(n), 2))
    idx = {a: i for i, a in enumerate(aristas)}
    tri = [(1 << idx[(a, b)]) | (1 << idx[(a, c)]) | (1 << idx[(b, c)])
           for a, b, c in combinations(range(n), 3)]
    return [sum(1 for t in tri if m & t == 0 or m & t == t) for m in range(1 << len(aristas))]

for n in (5, 6):
    c = triangulos_mono(n)
    print(f"K{n}: {len(c)} coloraciones, sin triángulo monocromático: {c.count(0)}, "
          f"mínimo de triángulos: {min(c)}")
print("K6, coloraciones por número de triángulos monocromáticos:", sorted(Counter(c).items()))

def mas_larga(a, creciente=True):
    """Longitud de la subsecuencia monótona más larga, por programación dinámica O(N^2)."""
    L = [1] * len(a)
    for j in range(len(a)):
        for i in range(j):
            if (a[i] < a[j]) == creciente:
                L[j] = max(L[j], L[i] + 1)
    return max(L)

rng = random.Random(0)
n = 4
peor = min(max(mas_larga(p), mas_larga(p, False))
           for p in (rng.sample(range(100), n * n + 1) for _ in range(500)))
print(f"\n500 secuencias de {n*n+1} números: la monótona más larga mide al menos {peor} (teorema: {n+1})")
extremal = [x for b in range(n) for x in range(n * (b + 1), n * b, -1)]
print("secuencia extremal de", n * n, "elementos:", extremal,
      " monótona más larga:", max(mas_larga(extremal), mas_larga(extremal, False)))

None of 32,768 K6K_6 colorings avoids a triangle, all have at least two, and K5K_5 has exactly the 12 pentagon colorings. For K7K_7 enumeration already has 221≈2×1062^{21} \approx 2\times 10^6 colorings; for K18K_{18}, needed to confirm R(4,4)=18R(4, 4) = 18 by brute force, 21532^{153}. Known Ramsey-number proofs combine pigeonhole-style arguments with heavily pruned computer searches.

Finally Lucas’s theorem against exact binomials and the triangle drawn modulo 2 and 3.

[ ]Lucas and the Sierpinski triangleBrowser
from math import comb
import numpy as np
import matplotlib.pyplot as plt

def binom_mod_lucas(n, k, p):
    r = 1
    while n or k:
        ni, ki = n % p, k % p
        if ki > ni:
            return 0
        r = r * comb(ni, ki) % p
        n, k = n // p, k // p
    return r

ok = all(binom_mod_lucas(n, k, p) == comb(n, k) % p
         for p in (2, 3, 5, 7) for n in range(120) for k in range(n + 1))
print("Lucas coincide con comb(n, k) % p para p = 2, 3, 5, 7 y n < 120:", ok)
print("C(n, k) impar  <=>  k & n == k:",
      all((comb(n, k) % 2 == 1) == (k & n == k) for n in range(200) for k in range(n + 1)))
impares = [sum(comb(n, k) % 2 for k in range(n + 1)) for n in range(128)]
print("impares por fila == 2^(unos de n):", all(impares[n] == 2 ** bin(n).count("1") for n in range(128)))
print("impares en la fila 100 =", impares[100], " (100 =", bin(100), ")")

N = 81
fig, ax = plt.subplots(1, 2, figsize=(9, 4.2))
for a, p in zip(ax, (2, 3)):
    M = np.full((N, N), np.nan)
    for n in range(N):
        for k in range(n + 1):
            M[n, k] = binom_mod_lucas(n, k, p)
    a.imshow(M, cmap="viridis", interpolation="nearest")
    a.set_title(f"C(n, k) mod {p}")
    a.set_xlabel("k"); a.set_ylabel("n")
plt.tight_layout(); plt.show()

The library version

FunctionReturnsNotes
math.comb(n, k), math.perm(n, k), math.factorial(n)exact integersPython integers have arbitrary precision: always exact
itertools.permutations, combinations, combinations_with_replacement, productlazy generatorslexicographic order by input position
scipy.special.comb(n, k)float64 by defaultvectorized but approximate; exact=True gives an exact integer
scipy.special.gammaln, math.lgammafloating-point log⁡Γ\log\Gammafor log⁡(nk)\log\binom{n}{k} with large nn, e.g. likelihoods
sympy.binomial, sympy.subfactorial, sympy.functions.combinatorial.numbers.stirlingexact expressionssymbolic too
[ ]Exact integers versus floating pointBrowser
import math, itertools
from scipy.special import comb as scomb, gammaln
import sympy
from sympy.functions.combinatorial.numbers import stirling

print("math.comb(52, 5) =", math.comb(52, 5), "  math.perm(10, 3) =", math.perm(10, 3))
print("itertools:", len(list(itertools.combinations(range(10), 3))), "combinaciones de 10 en 3")
print("scipy.special.comb(52, 5) =", scomb(52, 5), "  con exact=True:", scomb(52, 5, exact=True))

primero = next(n for n in range(2, 300) if scomb(n, n // 2) != math.comb(n, n // 2))
print(f"\nprimer n con comb(n, n//2) en float distinto del exacto: n = {primero}")
for n in (primero, 100, 1000):
    exacto = math.comb(n, n // 2)
    aprox = scomb(n, n // 2)
    print(f"  n = {n:4d}: error relativo de float = {abs(aprox - exacto) / exacto:.1e}"
          f"   error absoluto ≈ {abs(int(aprox) - exacto):.3g}")
print("C(1030, 515) en float:", scomb(1030, 515), "  exacto: un entero de",
      len(str(math.comb(1030, 515))), "cifras")
log_c = gammaln(1031) - 2 * gammaln(516)
print(f"log10 C(1030, 515) con gammaln: {log_c / math.log(10):.6f}"
      f"   exacto: {math.log10(math.comb(1030, 515)):.6f}")

print("\nsympy:", sympy.subfactorial(6), "desarreglos de 6;",
      sympy.binomial(52, 5), "manos de póker;",
      math.factorial(3) * stirling(6, 3), "sobreyecciones de 6 en 3")

Three observations. First, float64 binomials are unreliable even below 2532^{53}: scipy.special.comb(33, 16) already differs by one from 1 166 803 1101\,166\,803\,110, because intermediate products and quotients round; above 2532^{53} the exact result may not even be representable (consecutive float64 values are 2 or more apart). Relative error remains between 10−1610^{-16} and 10−1210^{-12}, but absolute error grows with the number (4.4×10134.4\times 10^{13} units for (10050)\binom{100}{50}), and an alternating sum such as inclusion–exclusion cancels huge terms to leave a small result, turning it into nonsense. Second, (1030515)≈2.9×10308\binom{1030}{515} \approx 2.9\times 10^{308} exceeds float64 maximum ≈1.8×10308\approx 1.8\times 10^{308}, and scipy returns inf; for probability use logarithms (gammaln) or ratios simplified before evaluation. Third, pure Python math.comb is exact and fast; floating point makes sense when vectorizing over NumPy arrays and accepting error, as discussed in floating-point representation.

Common mistakes

Exercises

QuizChoosing the model
You have 10 distinct jobs and 3 distinct GPUs; each job is assigned exactly one GPU (some may have no jobs). How many assignments exist?
NumericExactly one pair
How many 5-card poker hands (from a standard 52-card deck) contain exactly one pair: two cards of one rank and three cards of three other distinct ranks?
NumericNobody gets their hat
How many derangements (permutations without fixed points) of 6 elements exist?
NumericThree variables summing to 10
How many nonnegative integer solutions are there to x1+x2+x3=10x_1 + x_2 + x_3 = 10?
NumericWith an upper bound
How many integer solutions to x1+x2+x3+x4=12x_1 + x_2 + x_3 + x_4 = 12 satisfy 0≤xi≤50 \le x_i \le 5 for all ii?
NumericNo empty box
How many surjections are there from a 6-element set to a 3-element set?
NumericOdd entries in row 100
For how many k∈{0,…,100}k \in \{0, \dots, 100\} is (100k)\binom{100}{k} odd?
QuizWhere is the overcount?
To count 2-element subsets of {1,…,10}\{1, \dots, 10\} containing at least one even number, someone reasons: ‘choose an even number (5 ways) and any other element (9 ways): 5⋅9=455\cdot 9 = 45’. What happens?
ProofVandermonde by double counting
Prove: For integers m,n,r≥0m, n, r \ge 0, ∑k(mk)(nr−k)=(m+nr)\sum_k \binom{m}{k}\binom{n}{r-k} = \binom{m+n}{r}, where kk ranges over integers and (ab)=0\binom{a}{b} = 0 if b<0b < 0 or b>ab > a.
0
Take disjoint sets MM and NN with ∣M∣=m\abs{M} = m and ∣N∣=n\abs{N} = n (e.g. mm red and nn blue people).

Step 1 of 4. Which set do you count?

ProofOne divides the other
Prove: If n+1n + 1 distinct integers are chosen from {1,2,…,2n}\{1, 2, \dots, 2n\}, two exist such that one divides the other.
0
Let a1,…,an+1a_1, \dots, a_{n+1} be the chosen integers. Find pigeons and holes.

Step 1 of 4. What property of each number do you use?

CodeSurjections with exact integers
Implement surjections(n, k), the number of surjective functions from an n-element set to a k-element set, using inclusion–exclusion and exact integers (math.comb and integer powers). It must return 1 for n = k = 0, 0 if k > n or k = 0 < n, and work for large values such as surjections(200, 60) without losing a digit.
from math import comb

def surjections(n, k):
  """Número de funciones sobreyectivas de un conjunto de n elementos en uno de k."""
  # tu código: suma alternada sobre j de (-1)^j C(k, j) (k - j)^n
  return 0
Shift+Enter to run

Summary

Key idea
Counting constructs a bijection with something already countable: choice sequences (product), disjoint unions (sum), equal-sized classes (quotient) or stars-and-bars strings; overlapping cases require inclusion–exclusion’s alternating signs, and pigeonhole turns a count into an existence guarantee.
  • Sum, product, bijection and quotient rules yield four selection formulas: nkn^k, nk‾n^{\underline{k}}, (nk)\binom{n}{k} and (n+k−1k)\binom{n+k-1}{k}. Dividing by k!k! works only if every class has k!k! elements, which fails with repetition.
  • Stars and bars: x1+⋯+xk=nx_1 + \cdots + x_k = n with xi≥0x_i \ge 0 has (n+k−1k−1)\binom{n+k-1}{k-1} solutions; lower bounds use substitution and upper bounds inclusion–exclusion.
  • The binomial theorem counts words after commuting; it and double counting yield Pascal, hockey stick, Vandermonde and absorption. Modulo a prime, Lucas reduces (nk)\binom{n}{k} to base-pp digits.
  • Pigeonhole (and its ⌈∣A∣/∣B∣⌉\lceil \abs{A}/\abs{B}\rceil version) proves existence without construction: hash collisions, impossibility of compressing everything, Erdős–Szekeres and R(3,3)=6R(3, 3) = 6.
  • Inclusion–exclusion counts what avoids every bad property: derangements (Dn≈n!/eD_n \approx n!/e), surjections (∑j(−1)j(kj)(k−j)n\sum_j(-1)^j\binom{k}{j}(k-j)^n), φ(n)\varphi(n) and bounded stars and bars. Truncated, it gives Bonferroni and union bounds.
  • Check each formula against small brute-force cases and use exact integers: floating-point binomials lose digits (even below 2532^{53}) and overflow near 1.8×103081.8\times 10^{308}.