What Is a Computation?
What does it mean to compute, and is there a question no machine can answer?
The part opens with Euclid's algorithm played with two piles of pebbles, and with Hilbert's 1928 demand for a procedure that decides every mathematical statement. It follows the idea of a mechanical method through Babbage's engines and Lovelace's Note G to Turing's 1936 machine: a tape, a head and a finite table. The series' simulator runs a unary adder and a palindrome checker that needs about half of n squared steps on one tape and 3n + 3 on two, and a universal machine of 14 states runs the 2-state busy beaver from its description. The lambda calculus, counter machines, Rule 110 and Life compute the same functions, which is the evidence for the Church-Turing thesis. Then the part turns: Cantor's diagonal shows there are more problems than programs, and Turing's diagonal shows that no machine decides halting. It ends with the busy beavers, all 47,176,870 steps of the 5-state champion run on screen, and with Antihydra, a 6-state machine nobody can settle.
What you need. School arithmetic and the ability to follow a program. No earlier part is needed.
- Mathematics, ideas and history
- Hilbert, Turing machines, robustness, universality, λ-calculus, Church–Turing, diagonalization, halting, busy beavers
- What we build or compute
- a Turing machine simulator; BB(5) run for 47,176,870 steps
What you will be able to do
Degree
- Trace a Turing machine from its table, step by step, and draw its space-time diagram.
- Explain Cantor's diagonal argument and why it leaves most problems without a program.
- State the halting problem and retell the proof with the program D run on its own text.
Graduate
- Prove that Euclid's algorithm is correct by an invariant and terminates by a decreasing quantity.
- Simulate a k-tape machine on one tape and bound the slowdown by a quadratic.
- Prove that blank-tape halting is undecidable by a reduction from the halting problem.
Research
- Prove that S(n) eventually exceeds every computable function.
- Explain what a non-halting certificate is and how the deciders settled S(5).
- State why Antihydra's halting is open and derive the 1/phi ruin probability of its random model.
Industry
- Recognize interpreters, emulators and virtual machines as universal machines in software.
- Explain why a linter, a static analyzer or a virus scanner must approximate, citing Rice's theorem.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 34 min · Graduate 47 min · Research 52 min · Industry 36 min.
- 0PebblesDegree2 min
- 1Algorithms before machinesDegree4 min
- 2The enginesDegree4 min
- 3Hilbert's questionDegree2 min
- 4Turing's machineDegree4 min
- 5Programming with a tableDegree2 min
- 6More tapes, same powerGraduate3 min
- 7The universal machineDegree3 min
- 8Other machines, same powerGraduate4 min
- 9The Church-Turing thesisGraduate2 min
- 10More problems than programsDegree3 min
- 11The halting problemDegree3 min
- 12ReductionsGraduate2 min
- 13Busy beaversDegree3 min
- 14Frontier: the edge of the knowableResearch6 min
- 15What we will buildIndustry2 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.
PebblesDegree2 min
Here is a game for someone who knows nothing about numbers. Two piles of pebbles. One rule. If the piles are different, take away from the bigger pile as many pebbles as there are in the smaller one. When the piles are equal, stop.
Twenty-four and eighteen. The left pile is bigger, so take eighteen pebbles from it. Six and eighteen: now the right is bigger; take six from it. Six and twelve: take six again. Six and six. The piles are equal, and the game is over.
The player has computed something. Six is the greatest common divisor of twenty-four and eighteen: the largest number that divides both. This is Euclid's algorithm, written down about twenty-three hundred years ago. And the player needed no idea what a divisor is. They only had to follow the rule.
In 1928 the mathematician David Hilbert, with Wilhelm Ackermann, asked whether all of mathematics could be done this way. Is there a mechanical procedure, a set of rules for moving symbols like pebbles, that takes any precisely stated mathematical claim and decides, in a finite number of steps, whether it is true? Such a procedure would settle every open problem at once, by turning the crank. Hilbert called it the decision problem, the Entscheidungsproblem, and he expected the answer to be yes.
Eight years later, a twenty-three-year-old in Cambridge, Alan Turing, sent off his answer. The answer was no. No such procedure can exist. But to prove that, Turing first had to say exactly what a mechanical procedure is. His definition was a machine: a tape of symbols, a head that reads and writes one of them at a time, and a finite table of rules. He invented it to show what machines cannot do. It became the blueprint of every computer built since.
1Algorithms before machinesDegree4 min
Euclid's rule from the opening, with a short cut. Instead of taking the smaller pile away again and again, take it away as many times as it fits at once, and keep the remainder. Here it is on a picture. A rectangle, one thousand and seventy-one by four hundred and sixty-two. Cut off as many squares of side four hundred and sixty-two as fit: two of them. What is left is a strip one hundred and forty-seven wide. That is the remainder: one thousand and seventy-one is two times four hundred and sixty-two, plus one hundred and forty-seven.
Now the strip is the new rectangle. Cut squares of side one hundred and forty-seven from it: three fit. The remainder is a sliver twenty-one high. Cut squares of side twenty-one from the sliver. Seven of them fit exactly, with nothing left over. So squares of side twenty-one tile the sliver, and therefore the strip, and therefore the whole rectangle. Twenty-one is the greatest common divisor of one thousand and seventy-one and four hundred and sixty-two.
Why does this work for any two numbers? One step of the rule writes a as q copies of b, plus a remainder r. Take any number d that divides both a and b. Then it divides a minus q times b, which is r. And the other way: anything dividing b and r divides q times b plus r, which is a. So the pair a, b and the pair b, r have exactly the same common divisors, and so the same greatest one. Each step changes the numbers but not the answer. When the remainder reaches zero, the answer is in plain sight: the greatest common divisor of twenty-one and zero is twenty-one.
That kind of argument has a name. Something the procedure never changes is an invariant. Show it holds at the start, and that every step preserves it, and it holds when the procedure stops. Invariants are how we will prove circuits, algorithms and whole distributed systems correct, all through this series.
And why does it ever stop? Each remainder is smaller than the number it came from: four hundred and sixty-two, one hundred and forty-seven, twenty-one, zero. In general, b is bigger than the first remainder, which is bigger than the second, and so on, and none of them can be negative. A decreasing sequence of natural numbers cannot go on forever, so the procedure stops after at most b steps. A quantity that shrinks and cannot go below zero is the standard way to prove that a loop ends. We will meet it again in Part 2, and in Part 54, when we prove programs correct by machine.
How many steps does it take? Here is every pair of numbers up to two hundred and thirty-three, coloured by the number of steps, computed. Along the diagonal, one step. Near the axes, few. The bright rays are the hard cases. The very worst cases sit at consecutive Fibonacci numbers, where every quotient is one and the remainders shrink as slowly as they possibly can: the hardest pair here, 233 and 144, takes 12 steps. In 1844 Gabriel Lamé turned that into a theorem: the number of steps is at most five for each decimal digit of the smaller number. It is one of the first proofs of how long an algorithm takes, and Part 16 makes that question the centre of a whole subject.
2The enginesDegree4 min
Babbage's idea was that many tables need only addition. Take his favourite demonstration, the polynomial x squared plus x plus forty-one. Tabulate it: forty-one, forty-three, forty-seven. Next to each value, the difference to the next one: two, four. And the difference of the differences: two. For any quadratic, the second differences are constant. So once the first few rows are in place, every new row comes from two additions: add the constant to the difference, then add the difference to the value. No multiplication, no thought: a job for gears.
Watch the engine turn. The two flows down into the difference column, the difference flows into the value column, and a new value appears: fifty-three, sixty-one, seventy-one. Faster. Every value up to x equals thirty-nine is a prime number, which is why the polynomial was famous. At x equals forty it gives sixteen hundred and eighty-one, which is forty-one squared. The engine does not care. It only adds.
Babbage built a working piece of his Difference Engine. Then he designed something far more ambitious. The Analytical Engine had a store, holding a thousand numbers of forty digits each, and a mill that did arithmetic on numbers brought from the store. It was controlled by punched cards, borrowed from Jacquard's loom, which wove patterns from chains of cards. And crucially, the engine could skip or repeat cards depending on a result: it could branch and loop. In today's words: memory, a processor, a program, and output. It was never built; Babbage died in 1871 still revising the design. A Difference Engine was finally built from his drawings by the Science Museum in London, in 1991. It works.
In 1843 Ada Lovelace translated an Italian article about the Analytical Engine, and added seven notes of her own, three times as long as the article. The last, Note G, works out in full how the engine would compute the Bernoulli numbers, the coefficients of this series, which appear all over mathematics. They obey a recurrence: each one follows from all the ones before. So the program is a loop, with variables in the store reused on every pass. Here they are, computed exactly. Her table ends at the one she called B seven, which today is written B eight: minus one thirtieth. It is the first published program for a general-purpose machine, written for a computer that did not exist.
Lovelace saw further than the arithmetic. The engine weaves algebraic patterns, she wrote, the way the loom weaves flowers and leaves. Its operations need not be on numbers at all: if the relations of musical sounds could be expressed in its notation, it might compose elaborate pieces of music. Symbols, not just numbers. And she drew a line: the engine originates nothing; it does whatever we know how to order it to do. Turing would answer her objection by name, a century later. But notice what neither Babbage nor Lovelace asked: what can such orders do at all? What is the set of everything a machine like this could ever compute? That question came from somewhere else entirely: from the foundations of mathematics.
3Hilbert's questionDegree2 min
In the 1920s David Hilbert, the most influential mathematician of his time, set out a programme to put all of mathematics on such foundations. He wanted three things. Completeness: every true statement can be proved. Consistency: no contradiction can be proved. And decidability: a mechanical procedure that, given any statement, decides whether it can be proved. In his 1928 textbook with Wilhelm Ackermann the third wish became a precise problem: give a procedure that takes any formula of first-order logic and decides, in finitely many steps, whether it is valid. They called it the main problem of mathematical logic.
The first two wishes did not survive long, and the timing was cruel. On the seventh of September 1930, at a conference in Königsberg, a twenty-four-year-old Kurt Gödel announced that arithmetic contains true statements it cannot prove. The next day, in the same city, Hilbert gave a radio address that ended: we must know, we will know. Gödel's idea, in one picture: he built, inside arithmetic, a statement G that says of itself, I have no proof. If G had a proof, it would be false, and the system would prove something false. So, if the system is consistent, G has no proof, which is exactly what it says. G is true and unprovable. Completeness is impossible. We will prove this properly in Part 25, using what this part builds.
Gödel had not answered the third question, the decision problem, and there was a reason it was hard. To show that a procedure exists, you write one down and check it works. To show that none exists, you must say exactly what counts as a procedure, every possible procedure, and then rule them all out. Nobody had a definition of a mechanical procedure. In 1936, within weeks of each other, two people supplied one. In Princeton, Alonzo Church, with a calculus of functions. In Cambridge, Alan Turing, with a machine. Both answered Hilbert: no. We start with Turing's, because his definition is the one you can build.
4Turing's machineDegree4 min
Turing's definition came from looking at a person computing. Computing, he wrote, is normally done by writing symbols on paper, and we may suppose the paper is divided into squares, like a child's arithmetic book. What does the person actually do? They write symbols from some finite stock. They attend to only a few squares at a time; with a little more bookkeeping, to one. They have only finitely many states of mind that matter: remembering a carry, say. And each step is simple: change the symbol they are looking at, move their attention to a nearby square, and perhaps change their state of mind.
Turing then argued that nothing essential is lost if we simplify further. The page can be one long row of squares, a tape, unlimited in both directions. The person's attention becomes a head, sitting on one square. Their state of mind becomes one of finitely many states. What remains is a machine.
Here it is, written precisely. A Turing machine has a finite set of states, including a start state and one or more halting states, and a finite alphabet of tape symbols, including a blank. Its whole behaviour is one table, the transition function. In state q, reading symbol a, the table gives three things: a symbol to write, a direction to move, and the next state. A configuration is a snapshot: the state, the tape, and where the head is. Running the machine means applying the table to get from each configuration to the next, until it reaches a halting state, if it ever does.
Let's program one. Numbers in unary: three is one one one. On the tape, three, a plus sign, two. The head starts on the first square, in state A. The program is five rules. In state A, walk right over the ones. At the plus sign, write a one instead, and switch to state B. That joins the two numbers, with one one too many. In state B, walk right to the end, step back, and in state C erase the last one, and halt.
Now run it, one step at a time. Each step: find the rule for the current state and symbol, write, move, change state. After 8 steps the machine halts with five ones on the tape. Three plus two is five, and nothing in the machine knows what a number is.
There is a better way to see a whole run at once. Draw each configuration as a row of coloured squares, and stack the rows, so that time runs down the page. The head's square is outlined. You can read the program off the picture: a march to the right across the ones, the plus turning into a one, the turn at the end, the last one erased. This space-time diagram will let us look at runs of millions of steps, where watching one step at a time would take years.
One more machine, the simplest possible. One rule: in state A, reading a blank, write a blank, move right, stay in state A. It never reaches a halting state. It walks right forever, and its space-time diagram is a diagonal line that never ends. A Turing machine may halt, or it may run forever, and the table alone does not announce which. That gap, between running and halting, is where the whole second half of this part lives.
5Programming with a tableDegree2 min
A harder program. Given a string of zeros and ones, decide whether it is a palindrome: the same read forwards and backwards. Zero one one zero, yes. One zero zero one zero zero one, yes. Zero one one one, no. A plan a person might follow: erase the first symbol and remember it; run to the far end; check that the last symbol is the same, and erase it; run back; repeat until nothing is left. The tricky word is remember. The machine has no memory except the tape and its state.
So the memory goes into the state. Here is the whole program as a diagram: each circle is a state, each arrow a rule, labelled with the symbol read, and what to write and which way to move. State have zero means: I erased a zero, and I am carrying that fact to the far end. Have one is its twin. At the end, want zero checks that the last symbol is a zero, erases it, and hands over to back, which returns to the start. Any mismatch goes to reject. Running out of symbols goes to accept. Eight working states, eighteen rules.
Run it on zero one one zero. Watch the lit state carry the erased symbol across the tape. First pass: erase the zero, carry it to the end, match it, erase it, come back. Second pass: the same for the ones. Nothing left: accept, after 15 steps.
How long does this take? Here is a longer run as a space-time diagram: an input of twenty-four symbols, time running down. The head zig-zags across the whole remaining input on every pass, and the passes get shorter by two each time: a long sawtooth. Measured on inputs of every length up to sixty, the number of steps grows like the square of the length: about one half of n squared. Double the input, and the machine takes four times as long.
6More tapes, same powerGraduate3 min
Give the machine a second tape, with its own head. A rule now reads the symbols under both heads, writes on both tapes, and moves both heads, each left or right. Palindromes become easy. Copy the input onto tape two. Rewind tape one. Then compare: tape one read forwards, tape two read backwards, both at once.
On zero one one zero it takes 15 steps, the same as one tape. But the zig-zag is gone: each head crosses the input a fixed number of times.
Measured on every length up to sixty: with one tape the steps grow like n squared over two. With two tapes, exactly three n plus three. So a second tape makes the machine faster, and Hennie's theorem says no one-tape program can catch up. Does it also make the machine more powerful: can two tapes compute something one tape cannot?
No. Here is why. Take any configuration of a two-tape machine. Write both tapes onto a single tape, side by side, separated by a marker symbol. Mark where each head is with a dot: a dotted zero is just one more symbol in a bigger alphabet. To simulate one step, the single head sweeps right across everything, collecting the dotted symbols in its state, then sweeps back, writing the new symbols and moving the dots. If a dot runs into a separator, the tape is shifted along to make room.
Each simulated step costs a sweep over everything written so far, and after t steps that is at most about t cells. So t steps become about t squared. Here is the simulation, run for real on the palindrome machine: its steps grow quadratically, about 1.3 times the square of the two-tape step count at length sixty. Slower, much slower; but it computes exactly the same answers.
One more variation, and the most important. Let the table offer several possible moves in some configurations, and let the machine take any of them. A run is no longer a line but a tree of possibilities. Say the machine accepts if any branch accepts. This still computes nothing new: a deterministic machine can explore the tree, level by level, until it finds an accepting branch. But the tree can have two to the t branches after t steps, and the obvious simulation takes exponential time. Whether that exponential can always be avoided is the most famous open question in computer science, P versus NP: Part 26.
7The universal machineDegree3 min
Here is the busy beaver with two states from earlier, as a table: four rules. A Turing machine's table is finite. So it can be written down as a string of symbols. One way: number the states in unary, A is one, B is one one, halting is the empty string. Write each rule as its state, the symbol read, the symbol written, the direction, and the next state, separated by bars, and end each rule with a hash. The first rule, A reading zero, write one, move right, go to B, becomes one, bar, zero, bar, one, bar, R, bar, one one, hash. And so on for all four. The whole machine is now this string. Call it angle-bracket M: the description of M.
Now the key idea. A universal machine, U, takes two inputs: the description of any machine M, and an input w. It does exactly what M would do on w. It halts if and only if M halts, and it leaves the same output. In symbols: U of M and w equals M of w. Turing built one in the same 1936 paper, and his impossibility proofs depend on it. Here is ours, written for this series and tested against every machine it runs: 14 states, 29 rules, and three tapes. The first holds the description. The second is M's tape. The third holds M's current state, in unary.
Watch it work. At the start, tape three says M is in state one, A, and M's head on tape two reads a blank. U walks along the description, comparing each rule's state with tape three, one stroke at a time. The first rule matches: state A, reading zero. So U applies it to tape two: write a one, move right. Then it copies the rule's next state, one one, onto tape three, and rewinds. That was one step of M.
Faster now. Every step of M costs U a scan through the description. M takes six steps and halts with four ones on its tape. U takes 374 steps to do the same, and halts with the same four ones on tape two. A machine that can do what any machine does, given its description.
This is the idea that created software. Before it, a new task meant a new machine: one for tides, one for logarithms, one for ciphers. After it, one machine, and a description for each task. The description is data: it can be stored, copied, sent, and even computed by another program. The processor in your phone is a universal machine, and every app is a description. Emulators, the Java virtual machine and Python's interpreter are universal machines written in software, running on universal machines made of silicon.
8Other machines, same powerGraduate4 min
Church's answer to Hilbert looked nothing like a machine. His lambda calculus has only three kinds of expression: a variable; a function, lambda x dot M, meaning the function that takes x to M; and an application, M applied to N. And one rule of computation, beta reduction: a function applied to an argument becomes its body, with the argument substituted for the variable. There are no numbers. You build them. The number n is the function that applies f to x, n times: zero applies it no times, three applies it three times.
Addition is a function too. PLUS takes m and n, and returns the numeral that applies f n times, then m more times. Now compute two plus three by reduction alone. Each line comes from the one above by one beta step, on the highlighted part; this is the leftmost, outermost choice, which our reducer always takes. After 6 steps there is nothing left to reduce: lambda f x, f applied five times. Five. Multiplication and powers work the same way, with a few more steps. Church showed that numerals, pairs, lists, recursion, anything, can be built from functions alone.
Here is a third definition, and the opening's pebbles come back. A counter machine has a few bowls of pebbles, and a numbered list of instructions of only two kinds: add a pebble to a bowl; or, if a bowl is not empty, take a pebble out and go to one instruction, and if it is empty, go to another. This five-line program moves every pebble from bowl one into bowl zero, then every pebble from bowl zero into bowl two. It computes r zero plus r one. Three plus four: pebble by pebble, 24 steps, and bowl two holds seven. A person moving pebbles by these rules could compute anything a Turing machine can, given enough bowls, pebbles and patience. Minsky proved it.
In fact two bowls are enough. The trick is to pack all the counters into one number: two to the r zero, times three to the r one, times five to the r two. Adding one to r one means multiplying by three, which a second bowl can do as scratch space; testing r one means asking whether the number is divisible by three. We wrote a compiler that turns any program into a two-bowl program; the adder becomes 42 instructions. On three plus four, the big bowl starts with 648 pebbles and ends with 78,125, five to the seventh. Three bowls took 24 steps. Two bowls take 578,473. Same power; an exponential price.
Even simpler. A row of cells, each black or white. At every tick, each cell looks at itself and its two neighbours and changes colour by a fixed table of eight cases. This table is called Rule 110. Start it from a single black cell and draw each generation under the last. Structure appears: triangles, and gliders that crawl across the background and collide. In 2004 Matthew Cook proved that those collisions can be arranged to simulate any Turing machine. Eight cases, and nothing else, is universal.
In two dimensions, John Conway's Game of Life: a cell lives on with two or three live neighbours, and comes to life with exactly three. This pattern, Bill Gosper's glider gun, fires a stream of gliders forever. Streams of gliders can carry signals, and collisions can do logic. The Game of Life is universal too.
9The Church-Turing thesisGraduate2 min
Church and Turing had each given a precise definition of computing. On one side, the intuitive idea from chapter one: what a clerk can do by following rules. On the other, a mathematical object: what a Turing machine can do. The Church-Turing thesis says they are the same. Anything that can be computed by any mechanical procedure at all can be computed by a Turing machine. Notice what kind of statement this is. It cannot be proved, because one side of the equals sign is not mathematics. It is a claim that a definition is the right one.
Three reasons. First, every attempt to define computation, made independently by different people with different intuitions, gives exactly the same set of functions. Second, Turing's analysis starts from what a person computing actually does, and arrives at his machine, step by step. That is what convinced Gödel, who had been sceptical of Church's version. Third, ninety years later, after every programming language and every computer ever built, nothing computes a single function a Turing machine cannot. Gödel called Turing's definition precise and unquestionably adequate.
It is easy to read too much into it. It says nothing about speed: a Turing machine can compute what your laptop computes, only perhaps far more slowly. It says nothing about minds: it is a claim about procedures, which people can follow, not about everything people do. And it says nothing, by itself, about physics. Whether every physical process can be simulated by a Turing machine is a different question.
10More problems than programsDegree3 min
To compare problems with programs, we need to compare infinite sets, and the tool is Georg Cantor's, from the 1870s. Two sets have the same size if their elements can be paired off, one to one, with none left over. The natural numbers and the even numbers: pair n with two n. So there are as many even numbers as numbers. Pairs of numbers, and so fractions: lay them out in a grid and walk the diagonals, numbering as you go. Every pair gets a number. A set that can be listed like this, first, second, third, is called countable.
Programs are countable. Every program, and every machine description, is a finite string of symbols. List all finite strings: the empty string, then those of length one, then length two, in dictionary order, and so on. Every string appears somewhere in the list. So the machines can be listed too: M one, M two, M three, and so on, in the order of their descriptions. The list grows fast: there are about twenty thousand machines with two states, sixty trillion with five. But it is a list.
Now a set that is not countable. Suppose someone hands you a list of infinite sequences of zeros and ones, s one, s two, s three, and claims it contains every such sequence. Look at the diagonal: the first digit of the first sequence, the second digit of the second, and so on. Now build a new sequence, d, by flipping every diagonal digit. d is not s one: they differ in the first place. It is not s two: they differ in the second. It differs from the k-th sequence in the k-th place, so it is nowhere in the list. Any list misses something. The infinite sequences cannot be listed: there are strictly more of them than there are natural numbers.
Now connect the two. A yes-or-no problem about strings, like is it a palindrome, is exactly an infinite sequence of zeros and ones: for each string in our list, a one if the answer is yes and a zero if it is no. Empty string, yes. Zero, yes. One, yes. Zero zero, yes. Zero one, no. And every infinite sequence is some problem. So the problems are uncountable, and the programs are countable. There are strictly more problems than programs. Most problems, in a precise sense almost all of them, cannot be solved by any program. But notice: this argument proves they exist without naming a single one. Turing named one. And it is a problem you would very much like to solve.
11The halting problemDegree3 min
Every programmer has wanted this tool. You give it a program and an input, and it tells you whether the program will eventually finish, or hang forever. Call it H. It must always stop itself, and always be right. The set of program-input pairs where the program halts is called HALT, and H would be a decider for it.
Why not just run the program and see? Here are some real two-state machines from our list, each run on short inputs for ten thousand steps. A number means the machine halted after that many steps. A question mark means it was still running when we stopped. Running settles every halts answer, eventually. But a question mark is ambiguous: it might mean runs forever, or it might mean halts at step ten thousand and one. No finite amount of running can tell those apart. Running gives a recognizer for HALT, not a decider. Could something cleverer than running always work?
Turing's proof takes a few lines. Suppose H exists. Use it to build a new program, D. D takes a program p, and asks H: would p halt if it were given its own description as input? If H says yes, D deliberately loops forever. If H says no, D halts. D does the opposite of whatever H predicts. Now feed D its own description. Does D halt on D? If it halts, then H must have said it halts, so D loops forever. If it loops forever, H must have said it loops, so D halts. Both answers contradict themselves. The only way out is that H, the perfect halting checker, cannot exist.
It is Cantor's diagonal again. Make a table: the rows are all machines, M one, M two, and so on; the columns are their descriptions; each entry says whether that machine halts on that description. The diagonal is each machine run on its own description. D is built to do the opposite of the diagonal: where M i halts on its own description, D loops, and where M i loops, D halts. So D's row differs from every row in the table, in the diagonal place. D is not on the list. But the list contains every machine, and D would be a machine if H existed. So H does not exist.
And this answers Hilbert. Turing showed how to write down, for any machine, a formula of logic that is provable exactly when the machine halts. So a procedure that decided provability in logic would also decide halting. Halting cannot be decided, so neither can logic. The decision problem has no solution. Church reached the same answer with the lambda calculus, weeks earlier. No mechanical procedure can settle every mathematical question. The dream of Leibniz and Hilbert ends here, and the theory of computation begins.
12ReductionsGraduate2 min
One impossible problem gives many. Suppose you want to show that some problem B has no decider. Find a program that turns any halting question, a machine and an input, into a question about B, with the same answer. Then if B had a decider, you could chain them: transform, then decide. That would decide halting, which is impossible. So B has no decider either. This is called a reduction: halting reduces to B. It is the most used tool in this whole theory, and Part 26 runs on it.
A first example. Is there a decider for the simpler question: does M halt when started on a blank tape? Given any M and w, build a new machine, M sub w. It writes w on its tape, rewinds, and then behaves exactly like M. Building it is mechanical: a few new states in front of M's table. M sub w halts on a blank tape exactly when M halts on w. So a decider for blank tapes would decide halting. There is none. We will need this one in the next chapter.
In 1953 Henry Rice proved the general law. Any non-trivial property of the partial function a program computes is undecidable. Non-trivial means true of some computed functions and false of others. Questions about the text are fine: does it contain a while loop, is it under a hundred lines. Questions about the computed function are different: does it halt on every input, and does it return zero whenever it halts? We prove Rice's theorem in Part 25.
13Busy beaversDegree3 min
Here is a problem that looks innocent. In 1962 Tibor Radó proposed a game. Take every Turing machine with n states and two symbols. Start each one on a blank tape. Throw away the ones that never halt. Among the rest, find the one that runs longest before it stops: call its number of steps S of n. There are only finitely many machines with n states, so S of n is a perfectly definite number. The machines that achieve it are called busy beavers.
For two states we can simply try them all. There are twenty thousand, seven hundred and thirty-six. Run every one from a blank tape. Here are the ones that halt, by how many steps they take. Nine thousand seven hundred and eighty-four halt. The longest takes six steps, so S of two is six. Radó checked by hand that every machine still running after six steps runs forever. Here is the champion, the machine from earlier, writing four ones in six steps.
In 1990 Heiner Marxen and Jürgen Buntrock found a five-state machine: this table, ten entries. Started on a blank tape, it halts after forty-seven million, one hundred and seventy-six thousand, eight hundred and seventy steps. We ran it here, in compiled code, for every one of those steps. This is its whole run, squeezed into one picture: time runs down, each row is about 29,485 steps, and the tape spans 12,289 cells. In 2024 an online collaboration called bbchallenge proved that no halting five-state machine runs longer, so this is S of five. They had to show, for every one of the five-state machines, that it either halts within those forty-seven million steps or provably never halts, and the whole proof was checked by a computer proof assistant.
Zoom in on the first twelve hundred steps, cell by cell, and you can see the machine at work: a head sweeping back and forth across a growing block of ones, in a pattern that keeps almost repeating, and never quite does. That near-regularity, sustained for forty-seven million steps and then broken, is what made proving it so hard.
Radó's real point was that S is not merely hard to compute. No machine can compute it. Suppose one could. Then take any machine M with n states. Compute S of n. Run M on a blank tape for S of n steps. If it has halted, it halts. If it is still running, it can never halt, because no halting n-state machine runs longer than S of n. That would decide the blank-tape halting problem, which the last chapter showed is impossible. In fact S grows faster than any function a computer can compute: faster than exponentials, towers of exponentials, anything.
14Frontier: the edge of the knowableResearch6 min
Chapter thirteen ended on the proof that the five-state busy beaver is forty-seven million, one hundred and seventy-six thousand, eight hundred and seventy. How do you prove that a machine never halts, when running it cannot? With a certificate: a set of configurations that contains the starting one, is closed under taking a step, and contains no halting configuration. If such a set exists, the machine is trapped in it forever. It is the invariant method of Part 2, applied to machines. The bbchallenge collaboration built deciders that search for certificates of different shapes: a configuration that repeats; one that repeats shifted along the tape; tapes always built from a finite set of pieces; and, most powerful, sets of tapes recognised by a finite automaton, which Part 12 will build. Of about a hundred million five-state machines, all but thirteen fell to these deciders, and the thirteen sporadic machines each needed an argument of its own. Every step of the proof was checked by a proof assistant, which Part 54 explains.
BB(6) cannot be settled the way BB(5) was, because of machines like this one. It is called Antihydra: six states, one missing transition that would halt it, found by mxdys in June 2024. We ran it here for a hundred million steps. It has not halted, and its tape has grown to fourteen thousand cells. Racheline decoded what it is doing. It keeps two numbers, h starting at eight, and a counter c at zero. Each round, if h is even the counter goes up by two, and if h is odd it goes down by one; then h grows by half of itself, rounded down. The machine halts exactly when the counter reaches minus one. Each round takes the machine longer than the last, so our hundred million steps are only about twenty rounds.
Simulating the rule instead of the machine, a million rounds take half a minute. Here are the first ten: eight, twelve, eighteen, twenty-seven, forty. Even, even, even, odd. The counter climbs. If h were even half the time, the counter would rise by half a step per round on average. So plot what is left when that average is taken away. Over a million rounds the remainder wanders like a random walk, inside the dashed band where a fair coin's walk usually stays. After a million rounds the counter stands at nearly half a million, h is even forty-nine point nine five percent of the time, and h itself has grown to five hundred and eighty-five thousand bits. Antihydra halts only if, somewhere ahead, odd numbers come so often that this lead is wiped out.
How likely is that? Pretend the parities are fair coin tosses, and ask for q, the probability that the counter ever falls by one below where it stands. Either the first toss takes it down at once, or it goes up two, and must then fall three times, each with probability q. So q equals a half, plus a half q cubed. The cubic factors, and the root below one is the golden ratio's reciprocal, zero point six one eight. To reach minus one from a counter at c, it must fall c plus one times: probability q to the c plus one, which after our million rounds is ten to the minus one hundred and four thousand. Antihydra almost certainly never halts. But the parities are not coin tosses: they are fixed by arithmetic. Proving that they behave like coins is a problem of the same family as the Collatz conjecture and Kurt Mahler's three-halves problem of 1968, and nobody knows how to do it. Until somebody does, BB(6) is unknown.
Somewhere above six states, knowledge does not merely become hard; it becomes impossible. A Turing machine can search through every proof that follows from the axioms of set theory, halting if it ever finds a contradiction. If the axioms are consistent it never halts, and Gödel's theorem, which Part 25 proves, says the axioms cannot prove that. So its busy-beaver value can never be proved. In 2016 Adam Yedidia and Scott Aaronson built such a machine with seven thousand nine hundred and ten states. Since then, smaller ones: seven hundred and forty-five in 2023, six hundred and thirty-six in 2024, and four hundred and thirty-two in 2025, though the newest constructions have not yet been formally verified. So the busy-beaver function is known up to five, unknown at six, and unknowable by 432. Exactly where the line falls is one of the open questions at the border of computer science and logic, and a problem in this part's set.
15What we will buildIndustry2 min
Here is what this part found. Computing is following finite rules on symbols, and every reasonable way of saying that precisely gives the same answer. One machine, given a description, can do what any machine does. And some questions, including whether a program halts, no machine can answer.
The machine we build has a name: Pebble, after the calculi of the opening. Here is a preview. This is Euclid's algorithm from chapter one, in Pebble's own machine language: load the two numbers, then subtract, compare and swap, in a loop. The program runs on this series' Pebble emulator. Watch the registers: a zero and a one hold the two numbers, and t zero is scratch. After 60 instructions, a zero holds 21: the same twenty-one the rectangle gave us. In Part 6 we build this exact machine out of NAND gates, and it runs this exact program.
And one task will travel with us through every layer. The Job: count the words in thirty novels, the same thirty that AI, Built reads, and list the twenty most common. Each part that changes how fast or how cheaply the Job can be done adds a row to this ledger, with the time it takes: first on Pebble, gate by gate, in Part 6, then with pipelines, caches and more cores, a compiler, better algorithms, a database, a network, and finally a cluster and a cloud bill. The ledger will settle a question with data: which matters more, better hardware or better ideas?
Recap, problems, and where this comes backAll tracks2 min
What we found in this part. Euclid's rule, followed without understanding, and Lamé's bound on its worst cases. Turing's machine, which settles palindromes in n squared steps on one tape and three n on two. A universal machine, running any other from its description, for a price. Functions alone, bowls of pebbles, and a row of cells, all computing the same things. And beyond them all, the halting problem, and a five-state machine whose forty-seven million steps took the world until 2024 to understand.
Where this comes back. The universal machine becomes the stored-program computer of Part 6, the interpreters of Part 15 and the hypervisors of Part 32. Invariants and shrinking quantities are the proofs of Part 2 and Part 54. The finite control of a Turing machine is the finite automaton of Parts 5 and 12. The lambda calculus becomes the type theory of Part 14. Diagonalization and reductions drive Parts 25 to 27. And the extended thesis is the foundation of complexity theory, and the claim quantum computers test.
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 and change the universal machine this part used. The last, marked with a star, is a research problem, and its final step is open.
Next time: proof and counting. This part used proofs without saying what a proof is. Part 2 fixes that: logic, induction, invariants, and the counting that every later bound needs. It opens with a puzzle that sold millions of copies in 1880: slide the tiles to swap the fourteen and the fifteen. Can it be done? An invariant answers, in one line.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. The universal machine becomes the stored-program computer of Part 6, the interpreters of Part 15 and the hypervisors of Part 32. The finite control returns as the automata of Parts 5 and 12, the lambda calculus as the type theory of Part 14, and diagonalization and reductions drive Part 25, where Rice's theorem is proved. Pebble and the Job, introduced here, run through the whole series.
Key results
The part's results in one place, for revision.
Try it
Lab 1 · Busy beavers by brute force, and what one tape costs
Run all 20,736 two-state machines from a blank tape and find the one that halts last; rerun the 3- and 4-state champions; then time a one-tape palindrome checker on random palindromes and fit its step count.
python -m videos.cs.labs 1
needs numpy, scipy, matplotlib · download lab01.py ·
source on GitHubtwo-state machines 20,736 ((4n + 4)^(2n) at n = 2: 20,736)
halt within 40 steps 9,784 (the film: 9,784)
longest halting run 6 steps (S(2) = 6)
2-state champion 1RB1LB_1LA1RZ 6 steps, 4 ones
3-state champion 1RB1RZ_1LB0RC_1LC1LA 21 steps, 5 ones
4-state champion 1RB1LB_1LA0LC_1RZ1LD_1RD0RA 107 steps, 13 ones
palindrome of 60 symbols 1891 steps (n^2 / 2 = 1800)
fitted steps 0.500 n^2 + 1.50 n + 1.0 (the film: about 0.50 n^2)
Brute force settles S(2) = 6 because every two-state machine that has not halted by step 6 can be shown never to halt; the same search for five states took until 2024.
The code (98 lines; it asserts its own result)
"""Lab 1: run every two-state Turing machine, find the busy beaver, and time a palindrome checker."""
import numpy as np
from videos.coursekit import labs
from explainer.cs import turing
TITLE = "Busy beavers by brute force, and what one tape costs"
GOAL = ("Run all 20,736 two-state machines from a blank tape and find the one that halts last; rerun the 3- and "
"4-state champions; then time a one-tape palindrome checker on random palindromes and fit its step count.")
TASKS = [
"Raise LIMIT from 40 to 400 steps. Does any two-state machine halt later than step 6? Why can no limit prove it for three states?",
"Count the ones each halting two-state machine leaves (r.ones()) and find the largest: Rado's Sigma(2).",
"Write the binary incrementer of Problem 1 as a TM and check that it takes 2n + 2 steps on n ones.",
]
LIMIT = 40
# Palindromes on one tape (Chapter 5): cross off the first symbol, run to the far end, check the last, run back.
PALINDROME = turing.TM([
("start", "_", "_", "S", "accept"), ("start", "0", "_", "R", "have0"), ("start", "1", "_", "R", "have1"),
("have0", "0", "0", "R", "have0"), ("have0", "1", "1", "R", "have0"), ("have0", "_", "_", "L", "want0"),
("have1", "0", "0", "R", "have1"), ("have1", "1", "1", "R", "have1"), ("have1", "_", "_", "L", "want1"),
("want0", "0", "_", "L", "back"), ("want0", "1", "1", "S", "reject"), ("want0", "_", "_", "S", "accept"),
("want1", "1", "_", "L", "back"), ("want1", "0", "0", "S", "reject"), ("want1", "_", "_", "S", "accept"),
("back", "0", "0", "L", "back"), ("back", "1", "1", "L", "back"), ("back", "_", "_", "R", "start"),
], start="start", name="palindromes, one tape")
def all_two_state():
"""Every 2-state, 2-symbol table: each of the 4 entries writes 0 or 1, moves L or R, goes to A, B or halt (Z)."""
acts = [f"{w}{m}{n}" for n in "ABZ" for m in "RL" for w in "01"]
return [f"{a0}{a1}_{b0}{b1}" for a0 in acts for a1 in acts for b0 in acts for b1 in acts]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. every two-state machine, from a blank tape
tables = all_two_state()
halts = []
for t in tables:
r = turing.run(turing.TM.parse(t), max_steps=LIMIT)
if r.state in turing.HALT:
halts.append(r.steps)
halts = np.array(halts)
lab.row("two-state machines", f"{len(tables):,} ((4n + 4)^(2n) at n = 2: {(4 * 2 + 4) ** 4:,})")
lab.row("halt within 40 steps", f"{len(halts):,} (the film: 9,784)")
lab.row("longest halting run", f"{halts.max()} steps (S(2) = 6)")
assert len(tables) == 12 ** 4 and len(halts) == 9784
assert halts.max() == 6, "no two-state machine halts after step 6"
# 2. the champions, rerun
for n in (2, 3, 4):
table, steps, ones, _, _ = turing.CHAMPIONS[n]
r = turing.run(turing.TM.parse(table), max_steps=1000, record=True)
lab.row(f"{n}-state champion {table}", f"{r.steps} steps, {r.ones()} ones")
assert r.halted and (r.steps, r.ones()) == (steps, ones)
lo = min(h[1][0] for h in r.history) - 1
hi = max(h[1][0] for h in r.history) + 1
picture = turing.spacetime(r, lo, hi)
# 3. palindromes on one tape: right answers, and about n^2 / 2 steps
for _ in range(200):
w = "".join(rng.choice(["0", "1"], rng.integers(0, 13)))
assert turing.run(PALINDROME, w).state == ("accept" if w == w[::-1] else "reject"), w
ns = np.arange(4, 61, 4)
steps = []
for n in ns:
half = "".join(rng.choice(["0", "1"], n // 2))
r1 = turing.run(PALINDROME, half + half[::-1], max_steps=10 ** 5)
assert r1.state == "accept"
steps.append(r1.steps)
steps = np.array(steps)
coef = np.polyfit(ns, steps, 2)
lab.row("palindrome of 60 symbols", f"{steps[-1]} steps (n^2 / 2 = {60 * 60 // 2})")
lab.row("fitted steps", f"{coef[0]:.3f} n^2 + {coef[1]:.2f} n + {coef[2]:.1f} (the film: about 0.50 n^2)")
assert abs(coef[0] - 0.5) < 0.02, "the zig-zag costs n^2 / 2 to leading order"
lab.note = ("Brute force settles S(2) = 6 because every two-state machine that has not halted by step 6 can be "
"shown never to halt; the same search for five states took until 2024.")
fig, ax = labs.figure(2, size=(11, 4.4))
from matplotlib.colors import ListedColormap
ax[0].imshow(picture, aspect="auto", interpolation="nearest",
cmap=ListedColormap([labs.BG, labs.BLUE, labs.GREY, labs.GOLD]), vmin=0, vmax=3,
extent=(lo - 0.5, hi + 0.5, len(picture) - 0.5, -0.5))
ax[0].grid(False)
ax[0].set(title="The 4-state champion: 107 steps, 13 ones", xlabel="tape cell (blue: a 1, gold: the head)",
ylabel="step")
ax[1].plot(ns, steps, "o", color=labs.BLUE, label="one-tape palindrome machine")
grid = np.linspace(0, 60, 100)
ax[1].plot(grid, grid ** 2 / 2, color=labs.GOLD, label="n² / 2")
ax[1].plot(grid, 3 * grid + 3, color=labs.GREEN, ls="--", label="two tapes: 3n + 3")
ax[1].set(title="Steps to accept a palindrome of n symbols", xlabel="n", ylabel="steps")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Raise LIMIT from 40 to 400 steps. Does any two-state machine halt later than step 6? Why can no limit prove it for three states?
- Count the ones each halting two-state machine leaves (r.ones()) and find the largest: Rado's Sigma(2).
- Write the binary incrementer of Problem 1 as a TM and check that it takes 2n + 2 steps on n ones.
Problems, with solutions
Try each problem before opening its solution.
-
A binary incrementer. Design a Turing machine that adds one to a number written in binary, the head starting on the leftmost digit. How many steps does it take on 1ⁿ?
Solution
State A walks right over the digits (0 → 0, R and 1 → 1, R) and, on the blank after the number, steps left into state C. State C propagates the carry: on 1 write 0 and move left (staying in C); on 0 write 1 and halt; on the blank (the number was all ones) write 1 and halt. On 1ⁿ: n steps right, one step back, n carries, one final write: 2n + 2 steps, leaving 10ⁿ. (Checked with our simulator for n = 1, 3, 5: 4, 8 and 12 steps.)
-
Countable and uncountable. Show that the set of finite binary strings is countable, and the set of all subsets of ℕ is not.
Solution
List the strings by length, and those of equal length in dictionary order: ε, 0, 1, 00, 01, …. There are 2ᴸ − 1 strings shorter than L, so a string of length L appears at a position below 2ᴸ⁺¹: every string gets a finite position. For the subsets, suppose A₁, A₂, … listed them all, and let D = {k : k ∉ Aₖ}. For every k, D and Aₖ disagree about k, so D is not Aₖ: D is missing from the list, a contradiction.
-
Writing a 1. Prove that "does M ever write a 1, started on a blank tape?" is undecidable.
Solution
Reduce the blank-tape halting problem (Chapter 12) to it. Given M, build M′: it behaves like M but uses a fresh symbol 1′ wherever M uses 1 (so M′ never writes a real 1 while simulating), and wherever M would enter a halting state, M′ instead writes 1 and halts. M′ writes a 1 if and only if M halts on the blank tape, and M′ is built from M by a simple program. A decider for "ever writes a 1" would therefore decide blank-tape halting, which is impossible.
-
S increases. Prove S(n + 1) > S(n) for every n ≥ 1.
Solution
Take an n-state machine M that halts after S(n) steps. Its last step is a transition into the halting state. Add a new state Q, redirect that transition to Q, and give Q, on either symbol, the action "write the same symbol, move right, halt". The new machine has n + 1 states and takes exactly one more step: S(n + 1) ≥ S(n) + 1.
-
TIMES 2 2. Reduce (λm n f. m (n f)) 2 2 to normal form.
Solution
Normal order takes 7 β-steps: substitute m, then n; then the outer 2 applied to (2 f) gives λx. (2 f) ((2 f) x); unfolding the two copies of 2 f gives λf x. f (f (f (f x))), the numeral 4. (Our reducer,
explainer/cs/lam.py, prints every line.) -
Build: the universal machine's cost. Run U on the 4-state champion and measure its steps per simulated step; reorder the rules so the most used come first.
Solution
U takes 13,938 steps for M's 107: about 130 per simulated step, almost all spent scanning ⟨M⟩ for the matching rule and rewinding. Counting how often each rule fires and putting the busiest first inside each state's group (our encoding lists rules state by state) gives 13,308 steps, about 124 per step: a 4.5% saving, because most of the scan is spent crossing the rules of other states. Numbering the busiest states first helps more; a real interpreter replaces the scan by a jump to the right rule, the idea behind Part 15's dispatch tables.
-
★ Research: Antihydra. Antihydra's rule is h ← 8, c ← 0; each round c ← c + 2 if h is even and c − 1 if h is odd, then h ← h + ⌊h/2⌋; it halts when c = −1. (a) Show that, for steps of +2 and −1 with equal probability, the probability of ever falling one below the start is 1/φ. (b) Show that Antihydra never halts if and only if, for every N, at least a third of h₀, …, h_{N−1} are even. (c) Open: prove it.
What is known, and where to start. (a) Either the first step falls (probability ½) or it rises by two and must fall three times: q = ½ + ½q³, so (q − 1)(q² + q − 1) = 0 and the root below 1 is q = (√5 − 1)/2 = 1/φ. (b) After N rounds with E even values, c = 2E − (N − E) = 3E − N. The counter moves by +2 or −1, so it first goes negative exactly at −1, and c ≥ 0 for all N is the same as E ≥ N/3 for all N. (c) Nobody knows how. The parities of ⌊3h/2⌋-iterates are a deterministic sequence of the kind that defeats every known method: the same family as the Collatz conjecture and Mahler's 3/2 problem (does any α make the fractional parts of α(3/2)ⁿ stay below ½?). The bbchallenge wiki (Antihydra, Cryptids) collects what has been tried. Start from
compute_frontierinvideos/cs/cs1/compute.py: it runs a million rounds in half a minute with Python integers, and 3E − N is never negative in the first million rounds. A cheaper way to get the parities than carrying all of h (it has 0.585 N bits after N rounds) would be news in its own right.
Notes and sources
Sources
Books: Sipser, Introduction to the Theory of Computation, ch. 3–5; Petzold, The Annotated Turing; Moore & Mertens, The Nature of Computation, ch. 7; Minsky, Computation: Finite and Infinite Machines; Boolos, Burgess & Jeffrey, Computability and Logic; Davis, The Universal Computer; Hopcroft, Motwani & Ullman, Introduction to Automata Theory, Languages, and Computation.
Papers and documents: Lovelace, notes to Menabrea's Sketch of the Analytical Engine (1843); Babbage, Passages from the Life of a Philosopher (1864); Frege, Begriffsschrift (1879); Cantor (1891); Hilbert & Ackermann, Grundzüge der theoretischen Logik (1928); Gödel (1931); Church, "An unsolvable problem of elementary number theory" (1936); Turing, "On computable numbers, with an application to the Entscheidungsproblem" (1936); Rice (1953); Minsky (1961, 1967); Radó, "On non-computable functions" (1962); Hennie, "One-tape, off-line Turing machine computations" (1965); Lin & Radó (1965); Brady (1983); Cohen, "Computer viruses: theory and experiments" (1987); Marxen & Buntrock (1990); Cook, "Universality in elementary cellular automata" (2004); Yedidia & Aaronson, "A relatively small Turing machine whose behavior is independent of set theory" (2016); the bbchallenge collaboration, "Determination of the fifth busy beaver value" (2025).
About this partfrom its README
Part 1 of a sixty-one-part course in computer science (see the series plan and
the syllabus). Hilbert asked for a machine that settles every mathematical question; Turing defined
the machine, showed that one machine can imitate all others, and proved that no machine can do what Hilbert asked.
Every machine in this part runs on the computer that renders the video (compute.py); dates, quotations and the
proofs about busy beavers are the published ones, cited on screen.
- Pebbles. Euclid's algorithm played with two piles of pebbles by someone who knows nothing about numbers; calculus (Latin, a pebble) and the Roman counting board; Hilbert and Ackermann's Entscheidungsproblem (1928); Turing's answer (1936); objectives.
- 1. Algorithms before machines. Euclid with division, as squares cut from a 1071 × 462 rectangle (gcd 21); correctness by an invariant (the common divisors of (a, b) and (b, r) coincide), termination by a decreasing sequence of natural numbers; the steps for every pair up to 233, computed, with the worst cases at consecutive Fibonacci numbers and Lamé's bound (1844) checked on the whole grid; al-Khwārizmī and the informal definition of an algorithm.
- 2. The engines. Hand-computed tables and their errors (Babbage and Herschel, 1821); the method of finite differences on x² + x + 41, by additions only, primes up to x = 39 and 41² at x = 40; the Analytical Engine's store, mill and Jacquard cards, with branches and loops; Lovelace's Note G (1843) and the Bernoulli numbers, computed exactly (her B₇ is today's B₈ = −1/30); her notes on symbols, music, and the machine that originates nothing.
- 3. Hilbert's question. Leibniz's calculemus; Frege's Begriffsschrift (1879) and mechanically checkable proofs; Hilbert's three wishes (complete, consistent, decidable) and the 1928 decision problem; Gödel in Königsberg (7 September 1930) and Hilbert's radio address the next day; why "no procedure exists" needs a definition of procedure; Church and Turing (1936).
- 4. Turing's machine. Turing's analysis of a person computing (§9 of the 1936 paper) and the squared page that collapses to a tape; the formal definition and configurations; a unary adder (3 + 2) run rule by rule; the space–time diagram; a machine that never halts.
- 5. Programming with a table. Palindromes on one tape: the program as a state diagram whose states carry the erased symbol; a run on 0110 (15 steps); the zig-zag of a 24-symbol input; steps measured for every length up to 60 (≈ 0.50 n²); Hennie's Ω(n²) lower bound (1965) and the crossing-sequence idea.
- 6. More tapes, same power. Palindromes on two tapes in exactly 3n + 3 steps; one tape simulating k tapes (tracks and dots, two sweeps per step), with the simulation's head moves counted on the real palindrome machine; every other variant at polynomial cost; nondeterminism as a computation tree, and the exponential simulation that P versus NP asks about (Part 26).
- 7. The universal machine. A table written as a string ⟨M⟩; the universal machine U; ours (14 states, 29 rules, three tapes) running the 2-state busy beaver live, 374 of U's steps for M's 6; U's cost on the 2-, 3- and 4-state champions (62×, 107×, 130×); programs as data, and software.
- 8. Other machines, same power. The λ-calculus: syntax, β-reduction, Church numerals, PLUS 2 3 reduced in 6 normal-order steps; Minsky's counter machines as bowls of pebbles (3 + 4 in 24 steps), compiled to two counters (42 instructions, 578,473 steps, the Gödel number swelling to 5⁷); Rule 110 from one cell (Cook 2004); Gosper's glider gun in Conway's Life; the web of mutual simulations.
- 9. The Church–Turing thesis. The informal and the formal, and why the thesis cannot be proved; its evidence; what it does not say; three theses (Church–Turing, physical, extended) and the quantum challenge to the last.
- 10. More problems than programs. Pairing off infinite sets; Cantor's zig-zag through the pairs; programs as a countable list ((4n + 4)²ⁿ machines with n states, computed); Cantor's diagonal (1891); problems as infinite 0–1 sequences: uncountably many, so most have no program.
- 11. The halting problem. The decider H; a real halting table (two-state machines on inputs 1ʲ, run for 10,000 steps) and why "still running" is ambiguous; the program D and D(⟨D⟩); the diagonal argument; Turing's formulas for machines and the negative answer to Hilbert.
- 12. Reductions. Borrowing an impossibility; the blank-tape halting problem by the machine M_w; a gallery of undecidable questions; Rice's theorem (1953): behaviour against text; virus scanners (Cohen 1987), static analyzers, compilers, testing.
- 13. Busy beavers. Radó's S(n) (1962); all 20,736 two-state machines run (9,784 halt, the longest in 6 steps); the 3- and 4-state champions (Lin & Radó 1965, Brady 1983); the 5-state champion (Marxen & Buntrock 1990) run for all 47,176,870 steps, with 4,098 ones, in one picture and its first 1,200 steps in full; S(5) proved by the bbchallenge collaboration (2024, checked in Coq); S is uncomputable, by reduction from Chapter 12.
- 14. Frontier: the edge of the knowable. How BB(5) was proved: non-halting certificates (a set of configurations containing the start, closed under a step, with no halting configuration), the deciders (cyclers, translated cyclers, n-gram and repeated-word methods, finite-automata reduction) and the 13 sporadic machines. Knuth's arrows and the BB(6) record (Kropitz 2022, beyond 10↑↑15; mxdys 2025, beyond 10↑↑10↑↑10↑↑8). Antihydra (mxdys, 2024), run here for 100,000,000 steps without halting, and its Collatz-like rule (Racheline) run for a million rounds (c = 498,503); the gambler's-ruin heuristic, q = 1/φ, P(halt) ≈ 10^−104,181; why the parities resist proof (Collatz, Mahler's 3/2 problem). The smallest machines whose halting ZFC cannot settle: 7,910 states (2016), 745 (2023), 636 (2024), 432 (2025, not yet formally verified).
- 15. What we will build. The tower of abstractions and the eleven acts; Pebble-32, the computer of Part 6, running Euclid on this series' emulator (21, as the rectangle said); the Job and its ledger; in practice.
- Recap, problems, and where this comes back.
The 2025 and later claims about BB(6) are kept deliberately qualitative on screen ("the record has grown since"); the 2022 lower bound (more than 10↑↑15 steps) is the one stated.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: pebbles. Calculus means a small stone. Leibniz's calculemus; Hilbert's 1928 Entscheidungsproblem.
- Algorithms before machines: Euclid's GCD and its termination by descent; al-Khwārizmī; what "mechanical" meant.
- Babbage's Difference Engine: the method of finite differences, which tabulates a polynomial using additions alone (computed). The Analytical Engine; Lovelace's Note G and its Bernoulli-number program (1843).
- Hilbert's program, and Gödel 1931 in one picture (paid off in Part 25).
- Turing's machine (1936): tape, head, states, transition table. Definition card. Our simulator runs an incrementer and a unary adder, with the tape's space–time history drawn.
- Programming a Turing machine: palindromes, copying, binary addition, subroutines. What they cost: palindromes take Θ(n²) on one tape, by the crossing-sequence argument (sketched).
- Robustness: a multitape machine simulated on a single tape with quadratic slowdown (proved by construction); two-way tapes and larger alphabets; nondeterminism adds no power, at an exponential cost in simulation.
- The universal machine: encoding machines as strings, so that U simulates any M. This is the stored-program idea, paid off in Part 6. Small universal machines.
- Other models with the same power:
- the λ-calculus (Church 1936): Church numerals computing 2 + 3 on screen;
- μ-recursive functions;
- Minsky's two-counter machines, via the 2ᵃ3ᵇ trick;
- Post systems;
- Rule 110 (Cook 2004) and Conway's Life.
- The Church–Turing thesis: what it claims and what it doesn't. The physical thesis, and the extended (complexity-theoretic) thesis that Part 53 challenges.
- Diagonalization: Cantor's argument, then counting. There are countably many machines and uncountably many languages, so almost every problem is unsolvable.
- The halting problem: Turing's proof, animated as an infinite table with its diagonal flipped; the paradoxical program.
- Reductions: from halting to "does M ever print 1?" and "does M halt on a blank tape?". Rice's theorem as a teaser (proved in Part 25).
- Busy beavers (Radó 1962):
- BB(2) = 6, BB(3) = 21 and BB(4) = 107 steps, recomputed by our simulator;
- BB(5) = 47,176,870 (bbchallenge, Coq-verified, 2024). We run the champion for all 47 million steps and draw its tape;
- BB grows faster than any computable function (proved).
- What the series will do: computation is symbol manipulation, one machine is universal, and there are limits. Pebble, the tower and the Job are introduced.
- Outro: recap, problems, payoff cards.
Computed: the TM simulator (a C fast path for BB(5)); BB(2–5) step counts; a λ reducer counting β-steps; a Minsky machine; Rule 110 and a Life glider gun. Visuals: the tape with its history scrolling down like a cellular automaton; the diagonal flipping; BB(5)'s 47 million steps as one giant space–time image, the camera diving in; Church numerals as towers of function boxes. In practice: interpreters, emulators and VMs (the JVM, QEMU, smart-contract VMs) are universal machines; undecidability is why linters, static analyzers and virus scanners must guess. Reading: Turing 1936; Church 1936; Petzold, The Annotated Turing; Sipser ch. 3; Moore & Mertens, The Nature of Computation ch. 7; Minsky, Computation: Finite and Infinite Machines; Davis, The Universal Computer; Aaronson, "The Busy Beaver Frontier" (2020); bbchallenge (2024–25).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
二进制加一。 设计一台图灵机,把纸带上写成二进制的数加一,读写头从最左边的数字开始。输入 1ⁿ 时要走多少步?
解答
状态 A 向右走过所有数字(0→0,R;1→1,R),读到数字后面的空白时左移一格,进入状态 C。状态 C 负责进位:读到 1,写 0 并左移(仍在 C);读到 0,写 1 并停机;读到空白(原数全是 1),写 1 并停机。输入 1ⁿ:向右 n 步,回退 1 步,进位 n 步,最后写 1 共 1 步,合计 2n + 2 步,结果是 10ⁿ。(用本系列的模拟器验证:n = 1、3、5 时分别是 4、8、12 步。)
-
可数与不可数。 证明有限二进制串的集合是可数的,而 ℕ 的全部子集组成的集合不是。
解答
先按长度、再按字典序列出所有串:ε, 0, 1, 00, 01, …。长度小于 L 的串共有 2ᴸ − 1 个,所以每个串都在有限的位置上出现。 对子集:假设 A₁, A₂, … 列出了全部子集,令 D = {k : k ∉ Aₖ}。对每个 k,D 与 Aₖ 在“k 是否属于它”上意见相反,所以 D 不等于任何 Aₖ,不在这个列表里,矛盾。
-
写出一个 1。 证明“从空白纸带出发,M 是否会写出 1?”不可判定。
解答
把空白纸带停机问题(第12章)归约到它。给定 M,构造 M′:它模仿 M,但凡是 M 用 1 的地方都改用一个新符号 1′(因此模拟 期间 M′ 从不写真正的 1);凡是 M 要进入停机状态时,M′ 改为写一个 1 然后停机。于是 M′ 会写出 1 当且仅当 M 在空白纸带上停机,而 M′ 可以由 M 机械地构造出来。若能判定“是否会写出 1”,就能判定空白纸带停机问题,而这是不可能的。
-
S 严格递增。 证明对每个 n ≥ 1 都有 S(n + 1) > S(n)。
解答
取一台 n 状态、恰好走 S(n) 步停机的机器 M。它的最后一步是进入停机状态的一次转移。新增一个状态 Q,把这次转移改为进入 Q,并规定 Q 读到任何符号都“原样写回、右移、停机”。新机器有 n + 1 个状态,恰好多走一步,所以 S(n + 1) ≥ S(n) + 1。
-
TIMES 2 2。 把 (λm n f. m (n f)) 2 2 化为范式。
解答
按正规序需要 7 次 β 归约:先代入 m,再代入 n;外层的 2 作用在 (2 f) 上得到 λx. (2 f) ((2 f) x);展开两份 2 f, 得到 λf x. f (f (f (f x))),也就是丘奇数 4。(本系列的归约器
explainer/cs/lam.py会打印每一行。) -
动手:通用机的代价。 让 U 运行 4 状态的冠军机器,测量每模拟一步所需的步数;再把最常用的规则排到前面。
解答
M 走 107 步,U 要走 13,938 步:每模拟一步约 130 步,几乎全花在扫描 ⟨M⟩ 寻找匹配规则和倒带上。统计每条规则的使用 次数,并在每个状态内部把最常用的排在前面(我们的编码按状态分组列出规则),得到 13,308 步,约每步 124 步:只省了 4.5%,因为 扫描的大部分时间花在跨过其他状态的规则上。把最忙的状态编号排在前面效果更好;真正的解释器用一次跳转直接找到规则,这正是第15部分 分派表的思想。
-
★ 研究题:反九头蛇。 反九头蛇的规则是:h ← 8,c ← 0;每一轮,h 为偶数时 c ← c + 2,为奇数时 c ← c − 1,然后 h ← h + ⌊h/2⌋;c = −1 时停机。(a)证明对于等概率的 +2 和 −1 两种步长,有朝一日比起点低一的概率是 1/φ。(b)证明反九头蛇永不 停机,当且仅当对每个 N,h₀, …, h_{N−1} 中至少有三分之一是偶数。(c)未解:证明它。
已知什么,从哪里入手。(a)要么第一步就下降(概率 ½),要么先升二,然后必须下降三次:q = ½ + ½q³,于是 (q − 1)(q² + q − 1) = 0,小于 1 的根是 q = (√5 − 1)/2 = 1/φ。(b)N 轮中有 E 个偶数时,c = 2E − (N − E) = 3E − N。计数器每次 变化 +2 或 −1,所以它第一次变负时恰好是 −1;对所有 N 都有 c ≥ 0,等价于对所有 N 都有 E ≥ N/3。(c)没有人知道怎么做。⌊3h/2⌋ 迭代的奇偶性是一个确定性的序列,正是让所有已知方法失效的那一类:与考拉兹猜想和马勒的二分之三问题(是否存在 α,使 α(3/2)ⁿ 的小数 部分始终小于 ½?)属于同一家族。bbchallenge 维基(Antihydra、Cryptids 条目)收集了已有的尝试。从
videos/cs/cs1/compute.py里的compute_frontier入手:它用 Python 整数半分钟跑一百万轮,前一百万轮里 3E − N 从未变负。如果能找到比携带整个 h(N 轮后有 0.585 N 位)更便宜的办法得到奇偶性,那本身就是新闻。
Build the film
python -m videos.cs.cs1.compute # the part's numbers, into .cache/cs1
python tools/build.py cs1 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs1 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs1. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs1.compute # every number in the part (about two minutes)
python tools/build.py cs1 -q l # a 480p preview
python tools/build.py cs1 # 1080p
python tools/make.py cs1 # compute, then English and Chinese
The machines are in machines.py (the hand-written Turing machines, the single-tape simulation, the universal machine,
the counter-machine compiler, the cellular automata) and in the series toolkit (explainer/cs/turing.py,
explainer/cs/lam.py, explainer/cs/pebble/); tests/test_cs1_machines.py checks them.