Proof and Counting
How can you be certain that something is true for every case, or that a puzzle has no solution?
The part opens with the 15-puzzle craze of 1880 and the position with 14 and 15 swapped. Two numbers are watched through a random walk of slides, the swap parity of the sixteen squares and the blank's distance from home: they flip together, so their sum is an invariant, and a breadth-first search of the smaller puzzles reaches exactly the half of the positions it allows. From there the part supplies the mathematics the series stands on: truth tables and quantifiers, direct proof, contrapositive and contradiction, induction run as a recursive tromino tiling, structural induction, and invariants with decreasing measures. It then counts: bijections and Cantor's sizes of infinity, binomial coefficients, pigeonholes and Erdős-Szekeres, inclusion-exclusion and derangements, Catalan numbers, remainders and the Chinese remainder theorem, linearity of expectation, and the first facts about graphs. It ends at Ramsey numbers, where all 32,768 colourings of K6 are checked and the bounds on R(5,5) are still three apart.
What you need. School algebra. The epsilon-delta game of Chapter 1 is a callback to Analysis, Built, not a requirement.
- Mathematics, ideas and history
- logic and quantifiers, proof techniques, induction and invariants, relations and orders, cardinality, combinatorics, pigeonhole, inclusion–exclusion, Catalan, CRT, discrete probability
- What we build or compute
- the 15-puzzle's invariant; Catalan bijections
What you will be able to do
Degree
- Prove a statement by induction, by contrapositive and by contradiction, and say which fits.
- Find an invariant of a puzzle or a loop and use it to show a state is unreachable.
- Count permutations, combinations and derangements, and compute an expectation with indicators.
Graduate
- Prove Erdős-Szekeres by labelling each term with its longest increasing and decreasing runs.
- Derive the Catalan recurrence and closed form, and give a bijection between two Catalan families.
- Solve a system of congruences by the Chinese remainder theorem using Bézout coefficients.
Research
- Prove R(3,3) = 6 and the bounds between the square root of 2 to the k and 4 to the k for R(k).
- State the open problem of explicit Ramsey colourings and what the Paley graphs are known to give.
Industry
- Write a loop's invariant as an assertion and turn it into a property-based test.
- Use the union bound and base rates to estimate failures across many machines and false alarms.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 44 min · Graduate 48 min · Research 53 min · Industry 44 min.
- 0Fourteen, fifteenDegree3 min
- 1The grammar of truthDegree3 min
- 2Ways to proveDegree3 min
- 3InductionDegree3 min
- 4Induction on structuresDegree3 min
- 5InvariantsDegree4 min
- 6Sets, relations, functionsDegree3 min
- 7Sizes of infinityGraduate2 min
- 8CountingDegree3 min
- 9PigeonsDegree3 min
- 10Inclusion and exclusionDegree2 min
- 11Counting by recursionGraduate3 min
- 12NumbersDegree4 min
- 13ChanceDegree4 min
- 14GraphsDegree2 min
- 15Frontier: order in chaosResearch5 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Fourteen, fifteenDegree3 min
In the winter of 1880, half of America and much of Europe was pushing little tiles around a box. Fifteen numbered tiles, sixteen squares, one of them empty. You slide a tile into the empty square, one move at a time, and try to put the numbers in order. The famous version starts with everything in place except the last two: fourteen and fifteen are swapped. The puzzle-maker Sam Loyd later claimed he had offered a thousand dollars to anyone who could put them right. Nobody collected. People spent weeks on it.
Instead of trying, watch two numbers while the tiles move. The first: think of the empty square as a sixteenth tile. Every move swaps it with a neighbour. Count the swaps: is the arrangement an even or an odd number of swaps away from where it started? The second: how far the empty square is from its home corner, counting steps along rows and columns. Now move at random. The first number flips between even and odd on every move. So does the second, because the blank moves exactly one square. They flip together, so their sum is always even. Always.
That is the whole proof. Every move swaps the blank with one tile, so the parity of the swaps flips. Every move shifts the blank by one square, so the parity of its distance flips. So their sum is even at the start, and stays even forever. Now look at Loyd's position. It is one swap from the solved board: fourteen and fifteen. One is odd. And the blank is home, distance zero. Odd plus zero is odd. No sequence of moves, of any length, can get there. Weeks of sliding, settled in four lines. A quantity that no allowed move can change is called an invariant. William Johnson and William Story published this in 1879, and proved the converse too: every position with an even sum can be reached.
We can check the claim by brute force on smaller boards. Breadth-first search, which Part 18 builds properly, visits every position reachable from the solved one. On a two by two board, twelve of the twenty-four arrangements. On two by three, three hundred and sixty of seven hundred and twenty. On three by three, 181,440 of 362,880: exactly half, every time, and exactly the half the invariant allows. Here is how far those positions are from solved. The hardest need 31 moves, and there are only 2 of them. For the real puzzle, the reachable half is more than ten trillion positions. A search would take a while. The proof took four lines.
1The grammar of truthDegree3 min
A proposition is a statement that is either true or false: the blank is in its home corner; the swap parity is even. Logic builds bigger statements from smaller ones with a few connectives, and each one is defined completely by a truth table: one row for every way its parts can be true or false. Not P flips P. P and Q is true only when both are. P or Q is true when at least one is: in mathematics, or is inclusive. George Boole turned this into algebra in 1854. In Part 3 these tables become transistors.
The connective that causes the most trouble is implication: if P, then Q. Read it as a promise. If it rains, the street will be wet. The promise is broken in exactly one case: it rained, and the street is dry. If it did not rain, the promise was not tested, and it was not broken, so the implication counts as true, whatever the street is like. That is vacuous truth. Every unicorn in this room is purple: true, because there are no unicorns to be anything else. It sounds like a trick, but programs rely on it constantly. A loop that runs zero times satisfies every promise about each of its iterations.
A predicate is a statement with a blank in it: x is prime; y is bigger than x. Quantifiers fill the blanks. For all x, and there exists an x. Their order matters enormously. For every integer x there is a y bigger than x: true, take x plus one. There is a y that is bigger than every x: false, there is no largest integer. Same symbols, swapped, opposite meaning. To negate a quantified statement, push the not inward and flip each quantifier as it passes. Not everything is P means something is not P. Nothing is P means everything is not P.
There is a way to read long chains of quantifiers without getting lost: play them as a game. A skeptic chooses every for-all; a prover chooses every there-exists; the prover wins if the final statement holds. The statement is true exactly when the prover has a strategy that always wins. For every x there is a bigger y. The skeptic picks three; the prover answers four. Seven; eight. Ten; eleven. The strategy, y equals x plus one, always wins, so the statement is true. The game handles statements that defeat intuition. Here is continuity, from Analysis, Built: for every epsilon, there is a delta, such that for every x. Its negation, flipping each quantifier, is a winning strategy for the skeptic. Every specification in this series, from a cache that is coherent to a protocol that is safe, is a statement of this shape, and we prove it by showing that the prover always has an answer.
2Ways to proveDegree3 min
A proof is an argument that leaves no case out. The simplest kind is direct: start from what you are given, and walk to what you want. Claim: the sum of two odd numbers is even. An odd number is pairs, plus one left over. Put two of them together, and the two leftovers make one more pair. In symbols, with the definitions written out: two a plus one, plus two b plus one, is two times a plus b plus one, which is even. Notice that the proof starts by writing down exactly what odd means. Most proofs that go wrong go wrong there.
Sometimes the direct road is blocked. Claim: if n squared is even, then n is even. Starting from n squared equals two k gives you nothing to hold. So prove the contrapositive, which chapter one showed says exactly the same thing: if n is odd, then n squared is odd. Now it is one line. Two k plus one, squared, is two times something, plus one. Odd.
Proof by contradiction assumes the opposite of what you want, and derives something impossible. The classic: the square root of two is not a fraction. Suppose it were p over q, in lowest terms. Squaring, p squared is two q squared. Here is that equation as a picture. A square of side p has the same area as two squares of side q. Put the two smaller squares in opposite corners of the big one. They overlap in the middle, and they leave two corners uncovered. Since the areas match, the overlap has exactly the combined area of the two uncovered corners. But that is the same equation again, with smaller whole numbers: a square equal to two smaller squares. Repeat, and the numbers shrink forever, which whole numbers cannot do. So there was no p and q to begin with. The usual proof uses parity, the hook's tool, in the same way: it shows p and q are both even, so the fraction was not in lowest terms.
Another contradiction, perhaps the oldest proof still taught. Euclid: there are infinitely many primes. Suppose there were only finitely many. Multiply them all together and add one. Every prime on the list leaves remainder one when it divides that number, so none of them divides it. But every number bigger than one has some prime factor. That factor is a prime not on the list. Contradiction. A common misreading is that the new number is itself prime. Computing them: two plus one, three; up to two times three times five times seven times eleven, plus one: all prime. But the next one, thirty thousand and thirty-one, is fifty-nine times five hundred and nine: two new primes, exactly as the proof promised. The one after that is a product of three.
3InductionDegree3 min
Most of the statements this series cares about are about infinitely many things: every input, every length, every number of steps. You cannot check them one by one. Induction proves them all at once. Line up dominoes, one for each natural number. Show that the first one falls: that is the base case, P of zero. And show that whenever one falls, it knocks over the next: if P of n is true, so is P of n plus one, for every n. That is the inductive step. Then every domino falls. Nothing is checked infinitely many times; two finite arguments cover them all.
A first example: the sum one plus two up to n. A picture guesses the answer. Stack the numbers as a staircase. A second copy, turned over, completes an n by n plus one rectangle, so the sum is half of n times n plus one. Induction proves it. The base case: one is one times two over two. The step: assume it for n. Add the next number, n plus one, to both sides. Factor, and the right side is exactly the formula for n plus one. That pattern, a picture or an experiment to find the claim and induction to prove it, is how Part 16 will find and prove the running times of algorithms.
Induction is only as good as its step, and the step must work for every n. Here is a famous false proof. Claim: in any group of horses, all are the same colour. The base case, one horse, is fine. The step: take n plus one horses. The first n share a colour, by assumption. So do the last n. The groups overlap, so all n plus one share a colour. Where is the bug? Go from one horse to two. The first group is the first horse; the second group is the second horse. They do not overlap at all. The step fails at exactly one value of n, and one failure is enough to break the chain. Off-by-one errors in proofs and off-by-one errors in loops are the same mistake.
Induction does more than verify formulas. It builds things. Take a board two to the n squares on a side, remove any one square, and try to tile the rest with L-shaped pieces of three squares. Is it always possible? Induction on n. A one by one board with its square removed is empty: nothing to do. For the step, cut the board into four quarters. One of them contains the hole. Place one piece in the centre, covering a corner of each of the other three quarters. Now there are four smaller boards, each missing one square, and the induction hypothesis tiles each of them. Read the proof as a program, and it is a recursive algorithm. Here it runs: the centre piece first, then each quarter's centre piece, then each sixteenth's.
4Induction on structuresDegree3 min
Computer science is full of sets defined by rules rather than by formulas: strings a grammar allows, trees, expressions, lists, programs. Here is a small one: balanced parentheses. The empty string is balanced. And if s and t are balanced, then an open bracket, s, a close bracket, then t, is balanced. Nothing else is. Apply the rules, and the set grows: the empty string; one pair; two ways with two pairs; five with three. These are the Catalan numbers, and chapter eleven counts them.
To prove something about every member of such a set, follow the rules that build it. Claim: in a balanced string, reading left to right, the count of opens minus closes never goes negative, and ends at zero. Here is that count for one string, as a walk. Rule one: the empty string's walk starts and ends at zero. Rule two: assume the claim for s and t, and look at open, s, close, t. The open bracket lifts the whole of s's walk up by one, so it never drops below one and comes back to one. The close bracket brings it to zero, and t's walk goes from zero to zero. That is structural induction: prove the claim for what the base rules make, and show that every rule preserves it. Ordinary induction is the special case where the only rules are zero, and plus one.
The structure that matters most to us is the expression. Two plus three, times seven minus one, is a tree: operators at the nodes, numbers at the leaves. Its meaning is defined by recursion on the same structure. The value of a number is itself. The value of a sum is the sum of the values of its parts, and similarly for a difference and a product. Evaluate bottom up: five, six, thirty. Every interpreter is this definition, written as a program, and every fact about such programs, that evaluation always finishes, that a well-typed program never goes wrong, is proved by structural induction on this tree. Part 12 builds the parser that makes the tree; Part 14 proves the type system safe.
5InvariantsDegree4 min
The hook's proof is an example of the most useful method in this whole series. Model a process as a state machine: states, and the moves allowed between them. The puzzle's states are arrangements, a program's are the values of its variables, a network protocol's are the messages in flight. Some states are bad: a crash, two trains on one track, a lost bank transfer. We want to prove they can never be reached. Find a property that holds at the start, and that every move preserves. Then, by induction on the number of moves, it holds in every reachable state. If the bad states break it, there is no path to them. You never have to explore the states; you only have to check one move.
A puzzle from a film. Two jugs, three gallons and five gallons, no markings, a fountain. Measure out exactly four gallons, or the bomb goes off. You may fill a jug, empty it, or pour one into the other until one is full or the other is empty. Breadth-first search over the states finds a shortest solution, 6 moves. Fill the five. Pour it into the three, leaving two. Empty the three. Pour the two across. Fill the five again. Top up the three, which takes one gallon, and four are left.
Now the question an invariant answers: which amounts are possible at all? The invariant: every amount in either jug is a multiple of the greatest common divisor of the two sizes. It holds at the start, when both are empty. Filling gives A or B; emptying gives zero; pouring moves an amount that is a difference of multiples. Every move preserves it. With three and five, the gcd is one, and every amount is possible. With six and nine it is three: you can search for ever and never get four gallons, and the invariant tells you so before you start. The search finds the converse too: every multiple of the gcd up to the bigger jug does appear. That is Bézout's identity, and Euclid's algorithm again, in chapter twelve.
Invariants prove that nothing bad happens. A second tool proves that something good eventually does: the process stops. Here is a sorting rule: find two neighbours in the wrong order, and swap them. Repeat. Does it always stop? Count the pairs that are out of order, anywhere in the list. Each swap of neighbours fixes exactly that one pair and changes no other. So the count drops by one at every step, and a natural number cannot drop for ever. At most n choose two swaps. And when no swap is possible, the count is zero, so the list is sorted. That quantity is called a variant, or a ranking function. Euclid's remainders in Part 1 were one; Part 16 uses this very count to analyse sorting algorithms.
In programs, the same idea has a name you will see in code reviews: the loop invariant. This loop adds up the numbers below n. The comment states what is true at the top of every pass: s is the sum of everything below i. It holds before the first pass, when both are zero. Each pass adds i and moves i on, so it still holds. And when the loop ends, the invariant plus the fact that i is no longer less than n gives exactly the answer we wanted. Robert Floyd and Tony Hoare turned this into a logic of programs in the late 1960s, and in Part 54 a machine checks such proofs for us.
6Sets, relations, functionsDegree3 min
Almost everything in mathematics, and in a program's data, is built from three things: sets, relations and functions. A function from A to B sends every element of A to exactly one element of B. Draw it as arrows. It is one-to-one, injective, if no two arrows land on the same element. A hash function that is one-to-one never has a collision. It is onto, surjective, if every element of B is hit. And it is a bijection if it is both: a perfect pairing. Bijections are how we count, and how Part 1 compared infinite sets. Two finite sets have the same size exactly when there is a bijection between them.
A relation is just a set of pairs: which elements are related to which. One kind deserves a name. An equivalence relation is reflexive, symmetric and transitive: everything is related to itself, the relation goes both ways, and it chains. Example: call two integers related when their difference is a multiple of three. Then the integers fall apart into three classes, the numbers that leave remainder zero, one and two, and every integer is in exactly one. Every equivalence relation does this: it partitions its set into disjoint classes. The puzzle's positions under can reach each other form two classes, the hook's two halves. And in Part 5, the states of a machine that no input can tell apart form classes, and merging each class into one state gives the smallest machine possible.
A second kind of relation orders things. Take the divisors of sixty, related by divides. It is reflexive and transitive, and antisymmetric: if a divides b and b divides a, they are equal. That makes it a partial order. Partial, because some pairs are not comparable at all: four does not divide six, and six does not divide four. Draw only the steps that multiply by one prime, with bigger numbers higher, and the whole order is visible: a divides b exactly when there is an upward path. Any two elements here have a greatest common lower bound, their gcd, and a least common upper bound, their lcm. An order with that property is a lattice. Lattices come back twice: compilers use them to combine what they know about a program, and replicated databases use them to merge edits without conflicts.
7Sizes of infinityGraduate2 min
Part 1 said the fractions can be listed. Here is a listing so neat it was only found in the year 2000. Start with one over one. Every fraction p over q has two children: p over p plus q, and p plus q over q. The tree grows: one half and two; one third, three halves, two thirds, three. Neil Calkin and Herbert Wilf proved that every positive fraction appears in this tree exactly once, already in lowest terms. So reading it row by row lists them all, with no repeats: a bijection between the natural numbers and the positive rationals. There are exactly as many fractions as whole numbers.
Part 1's diagonal argument proves something more general. Take any set, and any way of assigning to each element a subset. Here, a goes to a and c; b to a alone; c to the empty set; d to everything. Collect the elements that are not in their own subset: b and c. Call it D. Could D be anyone's subset? If D were f of x, then x would be in D exactly when it is not. So no assignment hits every subset: the subsets of any set always outnumber its elements. Apply it again and again, and there is a tower of ever larger infinities, with no top. The same move, the diagonal, is what proved the halting problem undecidable, and Part 25 uses it once more to prove that some problems need more time than others.
8CountingDegree3 min
Counting is the raw material of every bound in this series: how many inputs, states, keys, paths. Two rules do most of the work. If you choose from one list or from a separate one, the counts add. If you make one choice and then another, and the second has the same number of options whatever the first was, the counts multiply. Three, then four: twelve outcomes, the leaves of this tree. The product rule is why passwords work. Eight characters, each one of sixty-two letters and digits: sixty-two to the eighth, about two hundred trillion. And why short ones do not: at ten billion guesses a second, all of them take about six hours.
Arrangements next. Line up n different things: n choices for the first place, n minus one for the second, and so on. n factorial. Choose two of four letters, in order: four times three, twelve. But if the order does not matter, each set of two was counted twice, once in each order. Divide by two factorial: six. In general, choosing k of n things, ignoring order, is n factorial over k factorial times n minus k factorial: n choose k. Counting too much and then dividing out a known overcount is one of the most useful tricks there is.
The numbers n choose k fit into a triangle. Each entry is the sum of the two above it. Why? A counting argument, with no algebra. To choose k people from n, either Ann is chosen, and you pick k minus one more from the others, or she is not, and you pick all k from the others. Those two cases are separate, so they add. A proof that counts the same set two ways is called a bijective, or combinatorial, proof. The same numbers expand powers. Multiply out x plus y, n times: each term picks x from some of the factors and y from the rest, and there are n choose k ways to pick x from k of them.
Colour each entry by whether it is odd. Sixteen rows show a pattern of triangles inside triangles. A hundred and twenty-eight rows, computed, and it is Sierpiński's triangle, a fractal, made of nothing but additions. There is an exact rule behind it, Lucas's theorem: n choose k is odd exactly when every binary one of k is also a one of n. So the number of odd entries in row n is two to the number of ones in n's binary form. Binary keeps turning up uninvited; from Part 3 on, it is all we have.
9PigeonsDegree3 min
The simplest principle in mathematics, and one of the most productive. Put seven pigeons into six holes, and some hole gets at least two. More generally, put N things into k boxes and some box holds at least N over k, rounded up. London has about nine million people, and nobody has more than about a hundred and fifty thousand hairs on their head. So at least sixty Londoners have exactly the same number of hairs, and nobody has to count.
Here is the principle proving something that does not look like pigeons at all. Paul Erdős and George Szekeres, 1935: any n squared plus one different numbers, in any order, contain a run of n plus one that only goes up, or only goes down. The run need not be adjacent; you may skip. Ten numbers, so n is three: there must be a run of four. Here one is: two, four, seven, eight.
The proof is a pigeonhole argument in disguise. Give every number a label: the length of the longest increasing run that ends at it, and the length of the longest decreasing run that ends at it. No two numbers get the same label. Take an earlier one and a later one. If the later is bigger, it can extend every increasing run that ends at the earlier one, so its first coordinate is bigger. If smaller, its second coordinate is. Now suppose there were no run of four. Every coordinate would be one, two or three: only nine possible labels. Ten numbers, nine labels, all different. Impossible. So a run of four exists.
One more, with a practical sting. There are eight bit strings of length three, and only seven strictly shorter ones, counting the empty string. A compressor that made every length-three input shorter would have to send two of them to the same output, and then it could not tell them apart when decompressing. The same count works at every length: two to the n strings of length n, two to the n minus one shorter ones. So every lossless compressor that shrinks some files makes others longer. Compressors win only because the files we care about are not random, which is where AI, Built began.
10Inclusion and exclusionDegree2 min
To count the elements in either of two sets, add their sizes. But the elements in both were counted twice, so subtract the overlap once. With three sets, add the three sizes, subtract the three pairwise overlaps, and then the very middle, which was added three times and subtracted three times, must be added back. Example: how many numbers from one to a hundred are divisible by two, three or five? Fifty, plus thirty-three, plus twenty; minus sixteen, ten and six for the multiples of six, ten and fifteen; plus three for the multiples of thirty. Seventy-four. The pattern continues for any number of sets, with alternating signs: inclusion, exclusion, inclusion.
Now a classic that inclusion-exclusion answers exactly. n people check their hats, and the hats are handed back at random. What is the chance that nobody gets their own? An arrangement with no fixed points is called a derangement. Count the bad orders instead, with inclusion-exclusion over the people who do get their own hat. Fix any k people: the other hats can go anywhere, n minus k factorial ways. Alternate the signs over k, and what remains is the derangements. For four people: twenty-four, minus twenty-four, plus twelve, minus four, plus one. Nine. Here they are, listed, checked by brute force.
Divide by n factorial to get the probability. One person: zero. Two: one half. Three: one third. Then it settles almost at once, at thirty-six point eight percent, and stays there: with ten people or ten thousand, the chance that nobody gets their own hat is the same. The formula is the series for e to the minus one, cut off after n terms. And a simulation agrees: shuffle a hundred thousand times, and about thirty-six point eight percent of shuffles have no fixed point, for ten people, for a deck of fifty-two, or for a thousand; with three it is exactly one third. Notice also that stopping the alternating sum early always overshoots or undershoots, by turns. Those Bonferroni bounds are how inclusion-exclusion is used when the full sum is too big to compute.
11Counting by recursionGraduate3 min
Some counts are easiest to describe in terms of smaller counts. In how many ways can a strip of length n be tiled with squares and dominoes? For length four, here are all five. Look at the first tile. If it is a square, what is left is a strip of length n minus one, tiled any way. If it is a domino, a strip of length n minus two. So the count is the sum of the two before it. One, one, two, three, five, eight: the Fibonacci numbers, which were Part 1's worst cases for Euclid's algorithm. A recurrence like this is also a program, and a slow one if you run it naively; Part 22 fixes that with dynamic programming.
Chapter four's balanced brackets had a count: one, one, two, five. Those numbers count a surprising number of other things. Here are the five bracket strings with three pairs. Each one is a full binary tree: open bracket, A, close bracket, B, becomes a root with A hanging to the left and B to the right. Five trees with three internal nodes. Each tree is a way to cut a pentagon into triangles with diagonals that do not cross: the root is the triangle on the bottom edge, and its subtrees triangulate the two sides. Five triangulations. And each bracket string is a mountain range: up for an open bracket, down for a close, never below sea level. Five again. These are bijections, so all four counts are the same number, for every size: the Catalan numbers.
The bracket picture gives a recurrence directly. Every non-empty string is an open bracket, a string A, a close bracket, and a string B. If A has k pairs, B has the remaining n minus k, and the two can be chosen independently: multiply, then add over k. The recurrence has a closed form too, one over n plus one, times two n choose n, which a clever bijection with paths proves. One, one, two, five, fourteen, forty-two, a hundred and thirty-two, growing roughly like four to the n. They count the ways to parse an ambiguous sentence, or to bracket a long product of matrices, which Part 22 optimizes.
12NumbersDegree4 min
Euclid's algorithm from Part 1 can do more than find the greatest common divisor. Run it on a table, and keep track of how each remainder is made. Every row holds a number r, and two integers s and t with r equal to s times 1071 plus t times 462. The first two rows are trivial. Each new row is the row two above, minus the quotient times the row above, so the invariant survives every step. At the end, twenty-one equals minus three times 1071 plus seven times 462. This is Bézout's identity: the gcd is always a combination of the two numbers, and the combinations are exactly its multiples. It is the converse the jugs were missing: four equals three threes minus one five.
Remainders have an arithmetic of their own. Two numbers are congruent modulo m when they leave the same remainder, that is, when m divides their difference. On a clock with ten marks, fourteen and four are the same place. You can add and multiply and reduce at any moment; the remainder comes out the same. What is the last digit of seven to the hundredth power? Work modulo ten. Seven, nine, three, one, and then it repeats: the hand comes home every four steps. A hundred is twenty-five fours, so seven to the hundred is congruent to one. The number has eighty-five digits, and we know the last one without computing any of the others.
Can you divide? Solving three x congruent to one, modulo ten, means finding a number that undoes multiplication by three. Try them all: x equals seven works, because twenty-one ends in one. But two x congruent to one has no solution at all: two x is always even, and so is anything congruent to it modulo ten. The rule is Bézout again. a has an inverse modulo m exactly when a and m share no factor: then a s plus m t equals one, and s is the inverse. The extended Euclidean algorithm finds it in a few steps even for numbers hundreds of digits long, which is exactly what RSA, in Part 30, needs.
A puzzle from a Chinese mathematics book of about the year four hundred, the Sunzi Suanjing. There is a number that leaves remainder two when divided by three, three when divided by five, and two when divided by seven. What is it? Three clocks, one hand each, all driven by the same x. Count up, and watch for the moment all three hands point at their targets. Twenty-three. And the pattern repeats only every three times five times seven, a hundred and five. There is a construction, not just a search: for each clock, a term that is right on that clock and zero on the other two, built from an inverse. Add them up. This is the Chinese remainder theorem. It lets a computer work with a huge number through its small remainders, in parallel, which Part 30 uses to make RSA four times faster.
13ChanceDegree4 min
Probability is counting, divided by counting, and it is where intuition fails most reliably. A game show. A car is behind one of three doors, goats behind the others. You pick a door. The host, who knows where the car is, opens a different door, always showing a goat, and offers you the chance to switch. Most people say it cannot matter: two doors left, fifty-fifty. Simulate three thousand games. Staying wins about a third of the time. Switching wins about two thirds. The reason: switching wins exactly when your first pick was wrong, and it was wrong two times in three. The host's choice gave you information, because it was not random. Whenever a probability argument feels slippery, list the outcomes, or simulate.
Conditional probability is the chance of one thing given that another happened, and it is the other half of the Monty Hall surprise. A disease affects one person in a hundred. A test catches ninety-nine percent of cases, but also flags five percent of healthy people. You test positive. How worried should you be? Count ten thousand people. A hundred are sick, and ninety-nine of them test positive. Nine thousand nine hundred are healthy, and four hundred and ninety-five of them test positive too. Of the five hundred and ninety-four positives, only ninety-nine are sick: one in six. Bayes' rule is this count written in symbols. When the thing you are looking for is rare, false alarms swamp it, which is the daily problem of every spam filter, fraud detector and intrusion alarm.
The most useful fact in discrete probability is almost too simple to believe. Back to the hats. On average, how many people get their own? Write the count as a sum of indicators: X i is one if person i gets their own hat, and zero otherwise. Each person has a one in n chance. The expectation of a sum is the sum of the expectations: n times one over n. One. For every n. The indicators are tangled together, since if one person has the wrong hat it changes the odds for the others, but linearity holds anyway, with no independence needed. The simulations agree, and the whole distribution of fixed points is close to the Poisson law with mean one. Part 16 uses exactly this trick, indicators and linearity, to show that quicksort makes about two n times the natural logarithm of n comparisons on average.
Often we cannot compute a probability exactly, but we can bound it, and the bound is what a guarantee is made of. Toss a hundred fair coins. What is the chance of seventy-five heads or more? Markov's inequality uses only the average, fifty: the chance is at most fifty over seventy-five, two thirds. True, and nearly useless. Chebyshev's inequality also uses the spread, the variance, twenty-five: being twenty-five away from the mean has chance at most twenty-five over six hundred and twenty-five, four percent. The exact answer is about three in ten million. Each extra fact about the distribution buys a much sharper bound, and Part 16 adds the Chernoff bound, which is close to the truth. And the crudest bound of all: the chance that any of several bad things happens is at most the sum of their chances. With twenty-three people, the chance that two share a birthday is at most two hundred and fifty-three pairs over three hundred and sixty-five, sixty-nine percent; the truth is fifty-one. Part 17 uses this to size hash tables.
14GraphsDegree2 min
The last structure of this part, and the one that carries networks, maps, dependencies and the web. The city of Königsberg had seven bridges joining two river banks, an island and a fourth piece of land. Could you take a walk that crosses every bridge exactly once? Leonhard Euler threw away everything but the land and the bridges: dots, and lines between them. A graph. Every time a walk passes through a place, it uses two bridges, one in and one out. So every place except the start and the end must touch an even number of bridges. In Königsberg all four touch an odd number. No such walk exists. That was 1736, and it was the first theorem of graph theory.
The bridge argument hides a fact about every graph. Label each vertex with its degree, the number of edges that touch it. Add up the degrees. Every edge has two ends, so every edge is counted exactly twice: the sum is twice the number of edges. In particular the sum is even, so the number of vertices with odd degree is even. At any party, the number of people who shook an odd number of hands is even. Counting the same thing two ways, again.
One more theorem, which Part 18 turns into an algorithm. Can the vertices be coloured with two colours so that every edge joins different colours? Colour one vertex blue, its neighbours orange, theirs blue, and so on outward. On this graph it works. On a cycle of five, going round, the colours alternate, blue, orange, blue, orange, blue, and the last vertex is next to the first: a clash. That is the whole story: a graph can be two-coloured exactly when it has no cycle of odd length. Going round an odd cycle flips the colour an odd number of times and you cannot get home; and if there is no odd cycle, colouring by the parity of the distance from a start vertex always works. Parity, one last time.
15Frontier: order in chaosResearch5 min
Part 2's pigeons lead straight to an open frontier. Among any six people, either three all know each other or three are all strangers; five people are not enough. Here are five, with friendship in red and strangers in blue: the red pentagon and the blue star contain no triangle of either colour. With six, pick one person. Five edges, two colours: by the pigeonhole principle, three of them share a colour, say red. If any two of those three people are friends, they make a red triangle with the first; if no two are, the three of them are a blue triangle. A computer agrees: of all thirty-two thousand ways to colour six people's relationships, not one escapes. Frank Ramsey proved in 1930 that this happens for any size: for every k there is a number R of k, a party size where k mutual friends or k mutual strangers are forced. Complete disorder is impossible.
For large k, two bounds from Paul Erdős have stood for most of a century. The upper one, with George Szekeres in 1935, is an induction of the kind Part 2 taught: R of k and l is at most R of k minus one and l, plus R of k and l minus one, which solves to a binomial coefficient, less than four to the k. The lower one, from 1947, founded the probabilistic method. Colour every relationship by tossing a coin, and count the expected number of one-colour groups of k, by linearity of expectation. Below two to the k over two people, that expectation is less than one, so some colouring has no such group at all. So R of k lies between root two to the k and four to the k: an exponential gap, and for seventy-five years nobody could move either end by an exponential factor.
Then, in 2023, the upper end moved. For decades the only progress shaved off factors smaller than any exponential: Andrew Thomason in 1988, David Conlon in 2009. In March 2023 Marcelo Campos, Simon Griffiths, Robert Morris and Julian Sahasrabudhe proved that R of k is less than four minus a small epsilon, all to the k, the first exponential improvement since 1935, with a new way of growing a structure they called a book. A year later Gupta, Ndiaye, Norin and Wei sharpened the same argument to three point eight to the k. The lower bound has not moved by an exponential factor since 1947. And the small cases remain brutally hard: the five-person number is between forty-three and forty-six, the forty-six proved in 2024 with linear programming and a large computer search. Erdős liked to say that if aliens demanded R of five on pain of destroying the Earth, we should set every computer to work on it; if they asked for R of six, we should try to destroy the aliens.
The lower bound hides a deeper open problem. Erdős's argument proves that good colourings exist, colourings of two to the k over two people with no large one-colour group, without saying where a single one of them is. Nobody knows how to build one by a rule that matches a random colouring: this has been open since 1947. Paley graphs are the natural candidate. We computed the largest group of friends in every Paley graph up to four hundred people: it grows like the logarithm, as a random colouring's would, nine at most here. But the best bound anyone can prove is of the order of the square root, near twenty at four hundred, far from the truth. Building order-free structures on purpose is the same problem as extracting good randomness from bad sources, which Parts 20 and 27 take up. It is the research problem of this part.
Recap, problems, and where this comes backAll tracks2 min
What we built in this part. Logic, the grammar of precise statements, and the ways to prove them: directly, by contrapositive, by contradiction, by cases, and by induction, on numbers and on structures. Invariants, which proved Loyd's puzzle impossible and every jug amount a multiple of the gcd. Counting: choices, Pascal's triangle and its hidden fractal, pigeonholes, inclusion and exclusion, and the Catalan numbers. And remainders, chance and graphs, the raw materials of cryptography, algorithms and networks.
Where this comes back. Invariants and decreasing measures prove algorithms in Part 16, locks in Part 33, replicated systems in Part 39, and whole programs by machine in Part 54. Structural induction is how Part 12 reasons about grammars and Part 14 about types. Counting and pigeonholes give the lower bounds of Part 16, the hash tables of Part 17 and the randomized algorithms of Part 20. Bézout, congruences and the Chinese remainder theorem are the arithmetic of Parts 29 and 30. Linearity of expectation and tail bounds analyse every randomized algorithm. And graphs carry Part 18's algorithms and Part 36's networks.
Seven problems, with full solutions in the part's notes. Pause on any of them. The sixth is a build problem: it asks you to run this part's search on a board we did not show. The last, marked with a star, is a research problem whose second half nobody has solved.
Next time: logic from switches. Chapter one's truth tables were written on paper. Part 3 builds them out of physical switches, relays first, the way Claude Shannon showed in 1937, then transistors. And it proves a surprising fact: one kind of gate, NAND, wired together enough times, computes every truth table there is. That gate is the only part Pebble needs.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Invariants and decreasing measures prove algorithms in Part 16, locks in Part 33, replicated systems in Part 39 and whole programs in Part 54. Structural induction is how Part 12 reasons about grammars and Part 14 about types. Counting and pigeonholes give the lower bounds of Part 16 and the hash tables of Part 17; Bézout and the Chinese remainder theorem are the arithmetic of Parts 29 and 30; graphs carry Parts 18 and 36.
Key results
The part's results in one place, for revision.
Try it
Lab 2 · An invariant against a search, and one fixed point on average
Breadth-first search from the solved 2 x 3 and 3 x 3 sliding puzzles, and compare the positions reached with the positions the parity invariant allows. Then shuffle n hats many times and compare the number that return to their owners with the derangement count and with linearity of expectation.
python -m videos.cs.labs 2
needs numpy, scipy, matplotlib · download lab02.py ·
source on GitHub2 x 3 puzzle: positions reached 360 of 720 (half: 360)
3 x 3 puzzle: positions reached 181,440 of 362,880 (half: 181,440)
3 x 3: hardest positions 31 moves, 2 of them (the film: 31 moves)
3 x 3 with 7 and 8 swapped invariant 1, reached: False
10 hats: mean number returned 1.009 (linearity of expectation: 1)
10 hats: P(nobody gets their own) 0.3659 (D(10)/10! = 0.3679, 1/e = 0.3679)
The search reaches exactly the half of the positions that the invariant allows, so the invariant is the whole story; and a random hand-back returns one hat on average whatever n is.
The code (114 lines; it asserts its own result)
"""Lab 2: search every position of the 3 x 3 sliding puzzle and check the invariant; then count hats that come home."""
from collections import deque
from math import factorial
import numpy as np
from videos.coursekit import labs
TITLE = "An invariant against a search, and one fixed point on average"
GOAL = ("Breadth-first search from the solved 2 x 3 and 3 x 3 sliding puzzles, and compare the positions reached "
"with the positions the parity invariant allows. Then shuffle n hats many times and compare the number "
"that return to their owners with the derangement count and with linearity of expectation.")
TASKS = [
"Start the search from the solved board with tiles 7 and 8 swapped. Which positions does it reach, and what is their invariant?",
"Drop the blank's distance from the invariant and use the permutation's parity alone. Find a single move that changes it.",
"Change hats to n = 3 and then n = 50. Which of the two results (mean 1, P(none) near 1/e) depends on n?",
]
def moves(rows, cols):
"""For each square the blank can be on, the squares it can swap with."""
out = []
for z in range(rows * cols):
r, c = divmod(z, cols)
out.append([rr * cols + cc for rr, cc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1))
if 0 <= rr < rows and 0 <= cc < cols])
return out
def invariant(board, rows, cols):
"""The parity of the permutation of all squares (the blank counts as the last tile) plus the blank's taxicab
distance from its home corner: every slide is one swap and moves the blank one square, so it never changes."""
n = rows * cols
perm = [(v - 1) % n for v in board]
seen, cycles = [False] * n, 0
for i in range(n):
if not seen[i]:
cycles += 1
while not seen[i]:
seen[i] = True
i = perm[i]
r, c = divmod(board.index(0), cols)
return (n - cycles + (rows - 1 - r) + (cols - 1 - c)) % 2
def bfs(rows, cols):
"""Distances from the solved board to every position that slides can reach. A board is a bytes object."""
start = bytes(list(range(1, rows * cols)) + [0])
table = moves(rows, cols)
dist = {start: 0}
queue = deque([start])
while queue:
b = queue.popleft()
z = b.index(0)
d = dist[b] + 1
for t in table[z]:
nb = bytearray(b)
nb[z], nb[t] = nb[t], 0
nb = bytes(nb)
if nb not in dist:
dist[nb] = d
queue.append(nb)
return dist
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the search against the invariant
for rows, cols in ((2, 3), (3, 3)):
dist = bfs(rows, cols)
total = factorial(rows * cols)
lab.row(f"{rows} x {cols} puzzle: positions reached", f"{len(dist):,} of {total:,} (half: {total // 2:,})")
assert len(dist) == total // 2
boards = list(dist)
sample = boards if total < 1000 else [boards[i] for i in rng.choice(len(boards), 20_000, replace=False)]
assert all(invariant(b, rows, cols) == 0 for b in sample), "every reached position keeps the invariant"
depth = np.bincount(list(dist.values()))
lab.row("3 x 3: hardest positions", f"{len(depth) - 1} moves, {depth[-1]} of them (the film: 31 moves)")
assert len(depth) - 1 == 31
swapped = bytes((1, 2, 3, 4, 5, 6, 8, 7, 0))
lab.row("3 x 3 with 7 and 8 swapped", f"invariant {invariant(swapped, 3, 3)}, reached: {swapped in dist}")
assert invariant(swapped, 3, 3) == 1 and swapped not in dist
# (the 2 x 3 boards are all checked; of the 3 x 3 boards, a random 20,000)
# 2. the hat check: n hats handed back at random
n, trials = 10, 40_000
perms = np.argsort(rng.random((trials, n)), axis=1)
fixed = (perms == np.arange(n)).sum(axis=1)
d = [1, 0]
for k in range(2, n + 1):
d.append((k - 1) * (d[-1] + d[-2])) # derangements: D(k) = (k - 1)(D(k-1) + D(k-2))
p0 = d[n] / factorial(n)
lab.row(f"{n} hats: mean number returned", f"{fixed.mean():.3f} (linearity of expectation: 1)")
lab.row(f"{n} hats: P(nobody gets their own)", f"{(fixed == 0).mean():.4f} (D({n})/{n}! = {p0:.4f}, 1/e = {np.exp(-1):.4f})")
assert abs(fixed.mean() - 1) < 0.03 and abs((fixed == 0).mean() - p0) < 0.012
assert abs(p0 - np.exp(-1)) < 1e-6
lab.note = ("The search reaches exactly the half of the positions that the invariant allows, so the invariant "
"is the whole story; and a random hand-back returns one hat on average whatever n is.")
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].bar(np.arange(len(depth)), depth, color=labs.BLUE, width=0.85)
ax[0].set(title="3 x 3 puzzle: positions at each distance from solved", xlabel="moves", ylabel="positions")
ks = np.arange(0, 7)
ax[1].bar(ks - 0.2, [(fixed == k).mean() for k in ks], width=0.4, color=labs.BLUE, label=f"{trials:,} shuffles of {n} hats")
ax[1].bar(ks + 0.2, [np.exp(-1) / factorial(int(k)) for k in ks], width=0.4, color=labs.GOLD, label="Poisson(1)")
ax[1].set(title="Hats returned to their owners", xlabel="number of fixed points", ylabel="probability")
ax[1].legend()
ax[0].set_axisbelow(True)
ax[1].set_axisbelow(True)
lab.fig = fig
return lab
Now change it
- Start the search from the solved board with tiles 7 and 8 swapped. Which positions does it reach, and what is their invariant?
- Drop the blank's distance from the invariant and use the permutation's parity alone. Find a single move that changes it.
- Change hats to n = 3 and then n = 50. Which of the two results (mean 1, P(none) near 1/e) depends on n?
Problems, with solutions
Try each problem before opening its solution.
-
Odd numbers. Prove 1 + 3 + 5 + ⋯ + (2n − 1) = n², and draw the picture.
Solution
For n = 1 both sides are 1. If the sum of the first n odd numbers is n², adding the next, 2n + 1, gives n² + 2n + 1 = (n + 1)². The picture: an n × n square of dots grows to (n + 1) × (n + 1) by adding an L-shaped border of n + n + 1 = 2n + 1 dots.
-
The 3 × 3 puzzle. Is the position with only 1 and 2 swapped, the blank in its corner, reachable?
Solution
No. It is one swap from the solved position (odd parity) with the blank at distance 0, so the invariant (swap parity + blank distance) is odd, while every reachable position has it even. Breadth-first search confirms it: the reachable set has 181,440 positions and this one is not among them.
-
Five points in a square. Show two of any 5 points in a unit square are at distance at most √2/2.
Solution
Cut the square into four squares of side 1/2. Five points, four squares: two points share a small square, and two points in a square of side 1/2 are at most its diagonal apart, √2/2.
-
Derangements. Count the derangements of 5 items and prove D(n) = (n − 1)(D(n − 1) + D(n − 2)).
Solution
D(5) = 120 − 120 + 60 − 20 + 5 − 1 = 44 (inclusion–exclusion, or brute force). For the recurrence, in a derangement person n gets some other person i's hat: n − 1 choices of i. Either i gets n's hat (a swap; the other n − 2 people are deranged: D(n − 2)), or i does not — then forbid i from n's hat as if it were their own, and the n − 1 people other than n form a derangement: D(n − 1). So D(n) = (n − 1)(D(n − 1) + D(n − 2)).
-
Three remainders. Find x with x ≡ 1 (mod 4), x ≡ 2 (mod 5), x ≡ 3 (mod 7).
Solution
M = 140. The terms: 1 · 35 · (35⁻¹ mod 4 = 3) = 105; 2 · 28 · (28⁻¹ mod 5 = 2) = 112; 3 · 20 · (20⁻¹ mod 7 = 6) = 360. Sum 577 ≡ 17 (mod 140). Check: 17 = 4 · 4 + 1 = 3 · 5 + 2 = 2 · 7 + 3.
-
Build: the 2 × 4 puzzle. Run the search on the 2 × 4 board.
Solution
bfs((1, 2, 3, 4, 5, 6, 7, 0), 2, 4)reaches 20,160 positions, half of 8!, as the invariant predicts; the farthest is 36 moves away, and there is exactly one such position. -
★ Research: Paley cliques. Compute the largest clique of the Paley graph P_q (vertices 0, …, q − 1, with i and j adjacent when i − j is a nonzero square mod q) for primes q ≡ 1 (mod 4) up to 1000. Open: prove that it is at most (log q)^C for some constant C.
What is known, and where to start.
compute_ramseyinvideos/cs/cs2/compute.pyfinds the clique numbers up to q = 400 in about seven minutes with a plain branch-and-bound; the largest found is 9. To reach 1000, use the symmetry: P_q is vertex-transitive (x ↦ x + c) and the map x ↦ ax for a square a fixes 0 and permutes its neighbours, so a largest clique can be assumed to contain 0 and 1, and the search runs inside the common neighbourhood of 0 and 1, about q/4 vertices. A colouring-based bound (as in Östergård's cliquer) prunes far more. On the theory side, the trivial bound is √q; Hanson and Petridis (2021) proved about √(q/2), and nothing of the form q^(1/2 − ε) is known for prime q. Random graphs have clique number about 2 log₂ q, and every computation suggests Paley graphs do no worse. A proof would give explicit Ramsey colourings, a problem open since 1947, and would matter for pseudorandomness (Parts 20 and 27).
Notes and sources
Glossary
不变量 invariant · 变式(递减量) variant · 结构归纳法 structural induction · 良序原理 well-ordering principle · 逆否命题 contrapositive · 逆命题 converse · 空真 vacuous truth · 单射 / 满射 / 双射 injection / surjection / bijection · 等价关系 equivalence relation · 偏序 partial order · 格 lattice · 链 / 反链 chain / antichain · 鸽巢原理 pigeonhole principle · 容斥原理 inclusion–exclusion · 错排 derangement · 卡特兰数 Catalan numbers · 第二类斯特林数 Stirling numbers of the second kind · 同余 congruence · 中国剩余定理 Chinese remainder theorem · 期望的线性性 linearity of expectation · 二分图 bipartite graph
Sources
Books: Lehman, Leighton & Meyer, Mathematics for Computer Science; Rosen, Discrete Mathematics and Its Applications; Graham, Knuth & Patashnik, Concrete Mathematics; Velleman, How to Prove It; Pólya, How to Solve It; Aigner & Ziegler, Proofs from THE BOOK; Stanley, Enumerative Combinatorics, vol. 1, ch. 1.
Papers and documents: Euler on the Königsberg bridges (1736); Boole, The Laws of Thought (1854); Johnson & Story, "Notes on the '15' puzzle", American Journal of Mathematics (1879); Erdős & Szekeres (1935); Dilworth (1950); Floyd, "Assigning meanings to programs" (1967); Hoare, "An axiomatic basis for computer programming" (1969); Vershik & Kerov, and Logan & Shepp (1977); Calkin & Wilf, "Recounting the rationals" (2000); Sunzi Suanjing (c. 400).
About this partfrom its README
Part 2 of a sixty-one-part course in computer science (see the series plan and
the syllabus). Part 1 used proofs without saying what a proof is; this part supplies the mathematics
the rest of the series stands on: logic, the standard proof techniques, induction and invariants, sets and orders,
counting, remainders, chance and graphs. Every search, count and simulation runs on the computer that renders the video
(compute.py), and each is checked there against the theorem it illustrates.
- Fourteen, fifteen. The 15-puzzle craze of 1880 and the position with 14 and 15 swapped; two numbers watched through a random walk (the swap parity of the sixteen squares and the blank's distance from home), which flip together; the invariant, and Johnson & Story (1879); breadth-first search over every position of the 2 × 2, 2 × 3 and 3 × 3 puzzles (exactly half reachable, exactly the half the invariant allows; the 3 × 3's hardest positions need 31 moves); objectives.
- 1. The grammar of truth. Propositions and truth tables for ¬, ∧, ∨ (Boole, 1854); implication as a promise, and vacuous truth; equivalence, the contrapositive against the converse, De Morgan's laws; predicates, ∀ and ∃, why their order matters and how negation flips them; a statement as a game between a prover and a skeptic, with continuity's ε–δ and its negation.
- 2. Ways to prove. Direct proof (odd + odd = even, as pairs of dots); contrapositive (n² even ⇒ n even); contradiction: √2 is irrational, with Tennenbaum's picture of infinite descent and the parity proof; Euclid's infinitely many primes, and the computed Euclid numbers (30,031 = 59 · 509); proof by cases; a non-constructive proof (√2^√2), and why constructive proofs are programs (Part 14).
- 3. Induction. Dominoes; 1 + … + n, found by a picture and proved by induction; strong induction and the smallest counterexample (every n ≥ 2 is a product of primes), and well-ordering; the "all horses are one colour" bug; tiling a 2ⁿ × 2ⁿ board with one square removed by L-trominoes, the proof run as a recursive algorithm (21 pieces).
- 4. Induction on structures. Sets defined by rules: balanced brackets; structural induction (the opens-minus-closes walk); binary trees have one more leaf than internal node (a 64-team knockout plays 63 games); expressions as trees and evaluation by recursion (Parts 12 and 14).
- 5. Invariants. The state-machine method; the 3- and 5-gallon jugs (a shortest solution in 6 moves, by search) and the gcd invariant for other jugs; a diagonal robot and the parity of x + y; termination by a decreasing measure (adjacent swaps and the inversion count); loop invariants, Floyd (1967) and Hoare (1969).
- 6. Sets, relations, functions. Injections, surjections, bijections; equivalence relations and partitions (residues mod 3, the puzzle's two classes, Myhill–Nerode in Part 5); partial orders and the Hasse diagram of the divisors of 60, lattices (Parts 13 and 39); chains, antichains and Dilworth's theorem (1950).
- 7. Sizes of infinity. The positive rationals listed without repeats by the Calkin–Wilf tree (2000); Cantor's pairing function; Cantor–Schröder–Bernstein; Cantor's theorem (no set maps onto its subsets) and the tower of infinities.
- 8. Counting. The sum and product rules (62⁸ passwords); permutations, combinations and dividing out an overcount; Pascal's triangle and its combinatorial proof; the binomial theorem; Pascal mod 2 is Sierpiński's triangle (128 rows, computed; Lucas's theorem); Vandermonde's identity by counting twice; stars and bars.
- 9. Pigeons. The pigeonhole principle and its generalization; Erdős–Szekeres (1935), proved by labels, with the sharp example and the longest increasing subsequence of random permutations (computed up to n = 100,000: ≈ 2√n); no lossless compressor shrinks every input.
- 10. Inclusion and exclusion. Unions of two and three sets (multiples of 2, 3 or 5 up to 100: 74); derangements and the hat-check problem (D₄ = 9, listed), D(n)/n! → 1/e with simulations, Bonferroni's alternating bounds; Euler's φ by inclusion–exclusion, for every n ≤ 60.
- 11. Counting by recursion. Square-and-domino tilings and Fibonacci; the Catalan numbers as brackets, binary trees, triangulations and mountain ranges, matched by bijections; the Catalan recurrence and closed form; Stirling numbers of the second kind and the Bell numbers.
- 12. Numbers. The extended Euclidean algorithm with its invariant, and Bézout (21 = −3 · 1071 + 7 · 462); congruences on a clock (the last digit of 7¹⁰⁰); inverses modulo m; Sunzi's remainder problem and the Chinese remainder theorem, by three clocks and by construction; unique factorization via Euclid's lemma.
- 13. Chance. Monty Hall, simulated (3,000 games); conditional probability and Bayes as counting (a test that is 99% sensitive but right about only one positive in six); indicators and linearity of expectation (one fixed point on average, for every n, against Poisson(1)); Markov, Chebyshev and the exact tail for 100 coins; the union bound and the birthday problem.
- 14. Graphs. Königsberg (Euler, 1736); the handshake lemma; trees and their equivalent definitions; two-colouring and odd cycles.
- 15. Frontier: order in chaos. Ramsey numbers. R(3,3) = 6 by the pigeonhole principle (the pentagon colouring of K₅; all 32,768 colourings of K₆ checked, none escapes); R(4,4) = 18 (the Paley graph on 17 vertices, its largest cliques and independent sets of size 3, checked; Greenwood and Gleason, 1955); Erdős and Szekeres's upper bound (1935) and Erdős's probabilistic lower bound (1947), √2ᵏ < R(k) < 4ᵏ; Thomason (1988) and Conlon (2009); the first exponential improvement, R(k) < (4 − 2⁻⁷)ᵏ (Campos, Griffiths, Morris and Sahasrabudhe, 2023), and 3.8^(k+o(k)) (Gupta, Ndiaye, Norin and Wei, 2024); 43 ≤ R(5,5) ≤ 46 (Angeltveit and McKay, 2024). The open problem of explicit Ramsey colourings: Paley clique numbers computed for primes up to 400 (they grow like log q; the provable bound is of order √q).
- Recap, where this comes back, in practice, problems.
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: the 14–15 puzzle (Loyd's $1,000 prize). An invariant (permutation parity plus the blank's row) proves the swapped position unreachable (Johnson & Story 1879). BFS on small sliding puzzles finds exactly half the positions reachable (computed).
- Propositions, connectives, truth tables; vacuous truth; equivalences; predicates and quantifiers. Negating ∀∃ statements, played as a game between a prover and a skeptic (callback to Analysis, Built 2's ε–δ).
- Proof techniques:
- direct proof, contrapositive and contradiction (√2 is irrational; there are infinitely many primes);
- proof by cases;
- constructive against non-constructive proof (irrational a, b with aᵇ rational).
- Induction: ordinary, strong and well-ordering, and why they are equivalent; the "all horses are one color" trap; tiling a 2ⁿ × 2ⁿ board with L-trominoes (recursion animated).
- Structural induction on recursively defined strings and trees, the form used for parse trees and type derivations (Parts 12 and 14).
- Invariants and variants: the state-machine method (Lehman, Leighton & Meyer); the Die Hard water jugs and their gcd invariant; termination by a decreasing measure. This previews Floyd and Hoare (Part 54).
- Sets, relations, functions:
- injections, surjections, bijections;
- equivalence relations and partitions (Myhill–Nerode in Part 5);
- partial orders and Hasse diagrams; lattices (dataflow in Part 13, CRDTs in Part 39);
- Dilworth's theorem, briefly.
- Cardinality: countable sets (ℚ by Cantor's pairing, computed); Cantor–Schröder–Bernstein; Part 1's uncountability, revisited.
- Counting I:
- the sum and product rules; permutations and combinations;
- bijective proofs; the binomial theorem; Pascal's triangle (Sierpiński mod 2);
- Vandermonde's identity, proved combinatorially; stars and bars.
- The pigeonhole principle:
- generalized pigeonhole;
- Erdős–Szekeres (a monotone subsequence of length √n, proved);
- no lossless compressor shrinks every input (callback to AI, Built 1).
- Inclusion–exclusion: derangements (→ 1/e), surjections, Euler's φ; Bonferroni bounds.
- Counting with recurrences: Fibonacci tilings; Catalan numbers with their bijections (parentheses, binary trees, triangulations, lattice paths, morphing into each other); Stirling numbers. Generating functions wait for Part 16.
- Number theory: divisibility; gcd and Bézout (Euclid from Part 1); congruences as clock arithmetic; the Chinese remainder theorem; the fundamental theorem of arithmetic. Part 30 builds RSA on these.
- Discrete probability:
- conditional probability and Bayes (Monty Hall); independence;
- linearity of expectation: in the hat-check problem, the expected number of fixed points is 1 for every n;
- indicator variables, the tool behind quicksort's analysis (Part 16);
- Markov, Chebyshev and the union bound.
- Graph basics: the handshake lemma; trees (n − 1 edges, and the equivalent definitions); bipartite iff no odd cycle (Part 18 builds on these). Outro.
Computed: reachable-state counts for sliding puzzles and the parity split; Cantor pairing; derangement ratios converging to 1/e; Catalan bijections enumerated; hat-check simulations; Erdős–Szekeres over random permutations. Visuals: the 15-puzzle with its invariant ticking; the recursive tromino tiling; Pascal's triangle turning into Sierpiński's; Hasse diagrams; Catalan objects morphing into one another. In practice: invariants are what assertions, code review and property-based tests check; counting is capacity planning; probability is load and failure analysis; all three appear in the first round of technical interviews. Reading: Lehman, Leighton & Meyer, Mathematics for Computer Science; Rosen, Discrete Mathematics and Its Applications; Graham, Knuth & Patashnik, Concrete Mathematics; Velleman, How to Prove It; Pólya, How to Solve It; Aigner & Ziegler, Proofs from THE BOOK; Stanley, Enumerative Combinatorics vol. 1 ch. 1; Johnson & Story 1879.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
奇数之和。 证明 1 + 3 + 5 + ⋯ + (2n − 1) = n²,并画出提示它的图。
解答
n = 1 时两边都是 1。若前 n 个奇数之和为 n²,再加上下一个奇数 2n + 1,得 n² + 2n + 1 = (n + 1)²。图:n × n 的点阵加上一条 由 n + n + 1 = 2n + 1 个点组成的 L 形边框,就变成 (n + 1) × (n + 1)。
-
3 × 3 华容道。 只交换 1 和 2、空格在角上的局面,能走到吗?
解答
不能。它与复原局面只差一次交换(奇置换),空格距离为 0,所以不变量(交换奇偶性 + 空格距离)为奇数,而每个可达局面它都是偶 数。广度优先搜索也证实了:可达集合有 181,440 个局面,这个局面不在其中。
-
正方形里的五个点。 证明单位正方形内任意 5 个点中,必有两点距离不超过 √2/2。
解答
把正方形切成四个边长 1/2 的小正方形。五个点放进四个小正方形,必有两点落在同一个里,而同一个小正方形里两点的距离不超过 它的对角线 √2/2。
-
错排。 求 5 个元素的错排数,并用计数论证证明 D(n) = (n − 1)(D(n − 1) + D(n − 2))。
解答
D(5) = 120 − 120 + 60 − 20 + 5 − 1 = 44。递推:错排中第 n 个人拿到某个人 i 的帽子,i 有 n − 1 种选择。若 i 恰好拿到 n 的帽子(两人互换,其余 n − 2 人错排:D(n − 2));否则,把“n 的帽子”当作 i 自己的帽子禁止 i 拿,除 n 以外的 n − 1 人构成一个错排: D(n − 1)。所以 D(n) = (n − 1)(D(n − 1) + D(n − 2))。
-
三个余数。 求 x,使 x ≡ 1 (mod 4),x ≡ 2 (mod 5),x ≡ 3 (mod 7)。
解答
M = 140。各项:1 · 35 · 3 = 105;2 · 28 · 2 = 112;3 · 20 · 6 = 360。和为 577 ≡ 17 (mod 140)。验证:17 = 4 · 4 + 1 = 3 · 5 + 2 = 2 · 7 + 3。
-
动手:2 × 4 华容道。 在 2 × 4 的棋盘上运行本部分的搜索。
解答
bfs((1, 2, 3, 4, 5, 6, 7, 0), 2, 4)可达 20,160 个局面,正好是 8! 的一半,与不变量的预言一致;最远的局面需要 36 步,而且只有一个。 -
★ 研究题:Paley 图的团。 对素数 q ≡ 1 (mod 4),q 不超过 1000,计算 Paley 图 P_q(顶点 0, …, q − 1,当 i − j 是模 q 的非零平方数时 i 与 j 相邻)的最大团。未解:证明它至多是 (log q)^C,C 是某个常数。
已知什么,从哪里入手。
videos/cs/cs2/compute.py里的compute_ramsey用普通的分支定界法,大约七分钟算出 q ≤ 400 的团数; 找到的最大值是 9。要算到 1000,就利用对称性:P_q 是顶点传递的(x ↦ x + c),而对平方数 a,映射 x ↦ ax 保持 0 不动并置换它的邻居, 所以可以假定最大团包含 0 和 1,只需在 0 和 1 的公共邻域(约 q/4 个顶点)里搜索。基于着色的上界(如 Östergård 的 cliquer) 剪枝效果好得多。理论上,平凡的上界是 √q;Hanson 和 Petridis(2021)证明了约 √(q/2),对素数 q 还不知道任何形如 q^(1/2 − ε) 的界。随机图的团数约为 2 log₂ q,而所有计算都表明 Paley 图不比它差。一个证明将给出显式的拉姆齐着色,这个问题自1947年起悬而未决, 也会影响伪随机性的研究(第20、27部分)。
Build the film
python -m videos.cs.cs2.compute # the part's numbers, into .cache/cs2
python tools/build.py cs2 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs2 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs2. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs2.compute # every number in the part; Ramsey enumeration can take several minutes
python tools/build.py cs2 -q l # a 480p preview
python tools/build.py cs2 # 1080p