---
title: "Turing Machines and Computability"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 15
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/15-turing-machines-and-computability
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 15 — Turing Machines and Computability

Some problems have no program at all: not a slow one, not a clever one, none. The school volumes showed one such problem, deciding whether a program halts, with a short argument about programs. This chapter rebuilds that result on a model of computation exact enough to prove things about: the [Turing machine](#def-b3-computability-tm). A simulator of thirty lines runs three machines; a second tape changes the speed but not the power; primitive and [$\mu$-recursive functions](#def-b3-computability-recursive) give a second model that computes the same functions; one program runs every machine from its description; and then the limits come, by diagonalisation and by reduction, up to Rice’s theorem, which says that no program can decide any [non-trivial property](#def-b3-computability-rice) of what programs compute. The weekend problem hunts the busy beavers of two states, a function no program computes.

**You already know.**

The grade-12 chapter on the [halting problem](#def-b3-computability-halting) showed that no program decides, for every program and input, whether that program halts: from a claimed [decider](#def-b3-computability-languages) it built a program that does the opposite of what the [decider](#def-b3-computability-languages) predicts about it. A set is countable when its elements can be listed as a sequence; the set of finite words over a finite alphabet is countable, and Cantor’s diagonal argument shows that the set of infinite sequences of bits is not (mathematics volumes). A finite automaton reads its input once, from left to right, and its transition function gives the next state from the current state and the letter read (Year 2 volume).

## 15.1 More problems than programs

Before any machine is defined, a count already shows that some problems have no program. A program, in any programming language, is a finite word over a finite alphabet; a problem with yes-or-no answers about natural numbers is a set of natural numbers, the numbers whose answer is yes.

**Theorem 15.1 (Countably many programs, uncountably many problems).**

There are countably many programs, and uncountably many sets of natural numbers. Some set of natural numbers is therefore decided by no program.

**Proof.** List the programs by length, and the programs of each length in alphabetical order: $P_0, P_1, P_2, \ldots$; every program appears at a finite position. Suppose the sets of natural numbers could be listed too, as $A_0, A_1, A_2, \ldots$. The set $D = \{n : n \notin A_n\}$ differs from each $A_n$ on the number $n$, so it is not in the list: a contradiction. If every set were decided by a program, mapping each set to the first program that decides it would list the sets, which is impossible. ∎

The proof shows that non-computable problems exist but names none. The rest of the chapter makes the argument concrete: it replaces “set of natural numbers” by a problem one would like to solve, and “program” by a precise machine.

## 15.2 Turing machines

Alan Turing’s paper “On computable numbers, with an application to the Entscheidungsproblem”, of 1936–37, defined the machine below to say what a person computing with pencil and paper can do.

**Definition 15.2 (Turing machine, configuration, transition function of a Turing machine).**

A *Turing machine* has a finite set of states with a start state, a finite tape alphabet containing a blank symbol, a tape of cells unbounded in both directions, and a head on one cell. Its *transition function* maps some pairs (state, symbol read) to a triple (new state, symbol written, move left, right or stay). A step applies it; the machine *halts* when no transition applies, and *accepts* if it halts in its accepting state. A *configuration* is the state, the tape contents and the head position: written $u\,[q]\,v$, the tape left of the head, the state, and the tape from the head on.

A finite automaton is the special case that only reads and only moves right. Writing, and moving back, is what makes the difference. The simulator stores the tape as a dictionary from positions to symbols, so the tape grows on demand in both directions.

```python
def run(delta, word, start="q0", max_steps=10_000, trace=None):
    """Run on `word`; returns (halted, state, tape contents, steps)."""
    tape = {i: c for i, c in enumerate(word)}
    head, state, steps = 0, start, 0
    while (state, tape.get(head, BLANK)) in delta:
        if steps == max_steps:
            return False, state, contents(tape), steps
        if trace is not None:
            trace(config(tape, head, state))
        state, tape[head], move = delta[(state, tape.get(head, BLANK))]
        head += {"L": -1, "R": 1, "S": 0}[move]
        steps += 1
    if trace is not None:
        trace(config(tape, head, state))
    return True, state, contents(tape), steps
```

***Listing 15.1.** The simulator’s main loop. A machine is a dictionary from (state, symbol) to (state, symbol, move). code/bachelor-3/15-computability/listings/tm.py*

Three machines: a binary increment, which walks to the last digit and carries leftwards; a palindrome checker over $\{a, b\}$, which erases the first letter, remembers it in its state, and checks it against the last; and a unary adder (`machines.py`).

```python
INCREMENT = {  # binary + 1: go to the last digit, then carry leftwards
    ("q0", "0"): ("q0", "0", "R"), ("q0", "1"): ("q0", "1", "R"),
    ("q0", B): ("carry", B, "L"),
    ("carry", "1"): ("carry", "0", "L"),  # 1 + carry = 0, carry on
    ("carry", "0"): ("done", "1", "S"), ("carry", B): ("done", "1", "S"),
}

PALINDROME = {  # cross off the first letter, check the last one matches, repeat
    ("q0", "a"): ("has_a", B, "R"), ("q0", "b"): ("has_b", B, "R"),
    ("q0", B): ("accept", B, "S"),
    ("has_a", "a"): ("has_a", "a", "R"), ("has_a", "b"): ("has_a", "b", "R"),
    ("has_a", B): ("end_a", B, "L"),
    ("has_b", "a"): ("has_b", "a", "R"), ("has_b", "b"): ("has_b", "b", "R"),
    ("has_b", B): ("end_b", B, "L"),
    ("end_a", "a"): ("back", B, "L"), ("end_a", B): ("accept", B, "S"),
    ("end_b", "b"): ("back", B, "L"), ("end_b", B): ("accept", B, "S"),
    ("back", "a"): ("back", "a", "L"), ("back", "b"): ("back", "b", "L"),
    ("back", B): ("q0", B, "R"),
}
```

***Listing 15.2.** The increment and the palindrome machines as transition tables. `B` is the blank. code/bachelor-3/15-computability/listings/machines.py*

```
$ python machines.py
[q0]1011
1[q0]011
10[q0]11
101[q0]1
1011[q0]_
101[carry]1_
10[carry]10_
1[carry]000_
1[done]100_
increment 0: 1
increment 111: 1000
increment 1001: 1010
palindrome 'abba': True, steps 15
palindrome 'aba': True, steps 10
palindrome 'abab': False, steps 5
palindrome '': True, steps 1
add 111+11: 11111
```

***Output 15.1.** The run of the increment machine on 1011, one [configuration](#def-b3-computability-tm) per line, then results on other inputs.*

![Left: the Pilot ACE, a cut-down version of Turing’s design (Science Museum, London). Right: the increment machine of after two steps.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computability/fig-8c349bf6da78.svg)

![Left: the Pilot ACE, a cut-down version of Turing’s design (Science Museum, London). Right: the increment machine of after two steps.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computability/img-73ca09ade92a.jpg)

*Left: the Pilot ACE, a cut-down version of Turing’s design (Science Museum, London). Right: the increment machine of [Output 15.1](#out-b3-computability-machines) after two steps.*

The photograph shows the Pilot ACE, one of the first computers built in the United Kingdom, a cut-down version of the design Turing wrote at the National Physical Laboratory; it first ran in 1950. Like every computer since, it is a universal machine in the sense of [Section 15.4](#sec-15-4): one machine that runs whatever program it is given.

### 15.2.1 More tapes, same power

A machine with several tapes, one head on each, is easier to program: the palindrome check copies the word to a second tape, then reads the first tape forwards and the second backwards.

**Definition 15.3 (Multi-tape Turing machine).**

A *multi-tape Turing machine* with $k$ tapes reads the $k$ symbols under its $k$ heads; its [transition function](#def-b3-computability-tm) gives the new state, the $k$ symbols written and the $k$ moves. The input starts on the first tape; the others start blank.

```python
PAL2 = {}
for x in "ab":
    PAL2[("copy", (x, B))] = ("copy", (x, x), ("R", "R"))  # copy, both move right
    PAL2[("rewind", (x, B))] = ("rewind", (x, B), ("L", "S"))  # tape 1 back to start
    for y in "ab":
        PAL2[("rewind", (x, y))] = ("rewind", (x, y), ("L", "S"))
        PAL2[("compare", (x, y))] = ("compare", (x, y), ("R", "L")) if x == y \
            else ("reject", (x, y), ("S", "S"))
PAL2[("copy", (B, B))] = ("rewind", (B, B), ("L", "L"))
for y in "ab" + B:
    PAL2[("rewind", (B, y))] = ("compare", (B, y), ("R", "S"))
PAL2[("compare", (B, B))] = ("accept", (B, B), ("S", "S"))
```

***Listing 15.3.** The two-tape palindrome machine: copy, rewind the first tape, compare. code/bachelor-3/15-computability/listings/multitape.py*

```
$ python multitape.py
 n   one tape   two tapes
  2          6           9
  4         15          15
  8         45          27
 16        153          51
 32        561          99
 64       2145         195
128       8385         387
```

***Output 15.2.** Steps to accept a palindrome of length $n$: about $n^2/2$ with one tape, $3n + 3$ with two.*

The one-tape machine walks the whole word for each pair of letters it crosses off: $(n + 1)(n + 2)/2$ steps. The two-tape machine walks the word three times. The gap is quadratic, and that is the worst that can happen.

**Theorem 15.4 (One tape simulates kkk).**

For every $k$-tape [Turing machine](#def-b3-computability-tm) there is a one-tape machine that halts on the same inputs with the same output; if the first takes $t \ge n$ steps on an input of length $n$, the second takes $O(t^2)$ steps.

**Proof idea.** Store the $k$ tapes on one, side by side: cell $i$ of the single tape holds a tuple of $k$ symbols, cell $i$ of each tape, each marked if a head is there (the alphabet of tuples is finite). One step of the $k$-tape machine becomes a sweep: left to right to read the $k$ marked symbols into the state, then back to write and move the marks. After $t$ steps the used part of the tape has at most $n + t \le 2t$ cells, so each sweep costs $O(t)$ steps and the whole run $O(t^2)$. ∎

Hartmanis and Stearns proved this in 1965, and used multi-tape machines for counting time because they are closer to real computers. A quadratic slowdown changes running times, which [Chapter 16](https://one-course.com/books/computer-science/5/en/chapter/16-time-and-space-complexity#ch-b3-complexity-classes) studies, but it changes nothing about what can be computed at all.

## 15.3 The Church–Turing thesis

The [Turing machine](#def-b3-computability-tm) is one model; the 1930s produced several others, built on quite different ideas. Alonzo Church’s 1936 paper used the $\lambda$-calculus of [Chapter 5](https://one-course.com/books/computer-science/5/en/chapter/5-the-lambda-calculus-and-operational-semantics#ch-b3-lambda-calculus). A third model builds functions on natural numbers from a few basic ones.

**Definition 15.5 (Primitive recursive function, μ\muμ-recursive function, Ackermann function).**

The *primitive recursive functions* are the functions on natural numbers built from zero, the successor $n \mapsto n + 1$ and the projections $(x_1, \ldots, x_k) \mapsto x_i$ by *composition* and by *primitive recursion*: $h(0, \vec y) = g(\vec y)$ and $h(n + 1, \vec y) = s(n, h(n, \vec y), \vec y)$. The *$\mu$-recursive functions* also allow *minimisation*: $\mu p(\vec y)$ is the least $n$ with $p(n, \vec y) = 0$, undefined if there is none. The *Ackermann function* is $A(0, n) = n + 1$, $A(m + 1, 0) = A(m, 1)$, $A(m + 1, n + 1) = A(m, A(m + 1, n))$.

Primitive recursion is a loop whose number of rounds is known before it starts, a `for` loop; minimisation is a `while` loop, which may never end. `primrec.py` builds both as Python combinators.

```python
def primrec(base, step):
    """h(0, ys) = base(ys); h(n + 1, ys) = step(n, h(n, ys), ys)."""
    def h(n, *ys):
        acc = base(*ys)
        for k in range(n):  # the loop runs exactly n times: no unbounded search
            acc = step(k, acc, *ys)
        return acc
    return h


add = primrec(proj(0), compose(succ, proj(1)))  # add(n, y) = n + y
mul = primrec(zero, compose(add, proj(1), proj(2)))  # mul(n, y) = n * y
power = primrec(compose(succ, zero), compose(mul, proj(1), proj(2)))  # y ** n


def mu(p):
    """Minimisation: the least n with p(n, ys) = 0. It may search for ever."""
    def f(*ys):
        n = 0
        while p(n, *ys) != 0:
            n += 1
        return n
    return f


@cache
def ackermann(m, n):
    if m == 0:
        return n + 1
    if n == 0:
        return ackermann(m - 1, 1)
    return ackermann(m - 1, ackermann(m, n - 1))
```

***Listing 15.4.** Primitive recursion, the arithmetic it builds, minimisation and Ackermann’s function. code/bachelor-3/15-computability/listings/primrec.py*

```
$ python primrec.py
add(3, 4) = 7  mul(3, 4) = 12  power(3, 2) = 2^3 = 8
isqrt(50) by minimisation = 7
A(0, n) for n = 0..5: [1, 2, 3, 4, 5, 6]
A(1, n) for n = 0..5: [2, 3, 4, 5, 6, 7]
A(2, n) for n = 0..5: [3, 5, 7, 9, 11, 13]
A(3, n) for n = 0..5: [5, 13, 29, 61, 125, 253]
```

***Output 15.3.** Addition, multiplication and powers by primitive recursion; a square root by minimisation; Ackermann’s function, whose rows grow by $n + 2$, $2n + 3$, $2^{n + 3} - 3$.*

Every [primitive recursive function](#def-b3-computability-recursive) is total, since every loop ends. Ackermann’s function is total too, and computed by the short recursion above, but it is not primitive recursive: each row grows like an iteration of the previous one, and every [primitive recursive function](#def-b3-computability-recursive) is eventually overtaken by one of the rows. Wilhelm Ackermann gave such a function in 1928, by a nested recursion; the two-argument form above follows Péter’s of 1935.

The fourth row already explodes: $A(4, 1) = 65{,}533$, and $A(4, 2) = 2^{65536} - 3$ has 19,729 digits.

**Theorem 15.6 (The models agree).**

The total functions computable by a [Turing machine](#def-b3-computability-tm), the total [$\mu$-recursive functions](#def-b3-computability-recursive), the total functions definable in combinatory logic (a relative of the $\lambda$-calculus) and the total functions computable by register machines with unbounded registers are the same class; so are the partial functions of the four models.

**Proof idea.** Each model simulates the others. A [Turing machine](#def-b3-computability-tm) can carry out composition, a bounded loop and an unbounded search on numbers written on its tape. Conversely, a [configuration](#def-b3-computability-tm) of a [Turing machine](#def-b3-computability-tm) can be coded as a number, one step is a [primitive recursive function](#def-b3-computability-recursive) of that code, and minimisation finds the first step at which the machine halts. ∎

Stephen Kleene gave minimisation its standard form in 1943, and the register machines are Shepherdson and Sturgis’s, of 1963.

**Definition 15.7 (Church–Turing thesis).**

The *Church–Turing thesis* states that every function computable by an effective procedure, one that a person could follow mechanically with unlimited paper and time, is computable by a [Turing machine](#def-b3-computability-tm).

The thesis is not a theorem: “effective procedure” is not a mathematical notion, so it cannot be proved. It is supported by [Theorem 15.6](#thm-b3-computability-equivalence): every attempt to define computation has given the same class. In practice it lets a proof describe an algorithm in words, or in Python, and conclude that a [Turing machine](#def-b3-computability-tm) exists.

## 15.4 A universal machine

A [Turing machine](#def-b3-computability-tm) is a finite table, so it can be written as a word, and a word can be the input of another machine.

**Definition 15.8 (Encoding of a machine, universal Turing machine).**

An *encoding* of [Turing machines](#def-b3-computability-tm) maps each machine $M$ to a word $\langle M \rangle$ over a fixed alphabet, so that the table of $M$ can be computed back from it. A *universal Turing machine* $U$ takes $\langle M \rangle$ and a word $w$, and behaves as $M$ on $w$: it halts if and only if $M$ halts, accepts if and only if $M$ accepts, and leaves $M$’s output.

`utm.py` numbers the states, with the start state first, and the symbols, writes each number in unary, and each transition as five numbers separated by 0s; transitions are separated by `#`. The universal program decodes the word and runs it.

```python
def encode(delta, start="q0"):
    """The machine as a string <M>; the start state gets number 1."""
    named = {s for s, _ in delta} | {t for t, _, _ in delta.values()}
    states = [start] + sorted(named - {start})
    symbols = sorted({a for _, a in delta} | {b for _, b, _ in delta.values()})
    num = {**{s: i + 1 for i, s in enumerate(states)},
           **{("sym", a): i + 1 for i, a in enumerate(symbols)}}
    code = []
    for (q, a), (r, b, m) in sorted(delta.items()):
        fields = [num[q], num[("sym", a)], num[r], num[("sym", b)], MOVES.index(m) + 1]
        code.append("0".join("1" * f for f in fields))
    return "#".join(code), symbols


def universal(code, symbols, word):
    """Decode <M> and run it on word: one program for every machine."""
    delta = {}
    for t in code.split("#"):
        q, a, r, b, m = (len(f) for f in t.split("0"))
        delta[(q, symbols[a - 1])] = (r, symbols[b - 1], MOVES[m - 1])
    return run(delta, word, start=1)
```

***Listing 15.5.** [Encoding](#def-b3-computability-universal) a machine over $\{0, 1, \#\}$, and the universal program that runs an encoded machine. code/bachelor-3/15-computability/listings/utm.py*

```
$ python utm.py
symbols ['0', '1', '_'] are 1, 2, 3; <INCREMENT> has 85 characters
  110101110110111      = [2, 1, 3, 2, 3]
  110110110101         = [2, 2, 2, 1, 1]
on 1011: directly 1100, through the universal program 1100
on 111: directly 1000, through the universal program 1000
```

***Output 15.4.** The increment machine as 85 characters, and the same results through the universal program.*

A first version numbered the start state 4 instead of 1 and printed its inputs unchanged: `named - {start}` had been written inside a union, and `-` binds more tightly than `|` in Python, so the start state was subtracted from one operand only and listed twice. The test that compares direct and universal runs over every word of length 6 catches that kind of slip. Turing built a universal machine in his 1936–37 paper, as a [Turing machine](#def-b3-computability-tm), and used it to prove that some problems have no machine. `universal` is the same thing in Python; by the thesis, it is a [Turing machine](#def-b3-computability-tm) too.

**Definition 15.9 (Decider, decidable language, recognisable language).**

A machine *recognises* the language of the words it accepts. A language is *recognisable* (semi-decidable, recursively enumerable) when some machine recognises it: on a word of the language it halts and accepts; on another word it rejects or runs for ever. A *decider* is a machine that halts on every input; a language is *decidable* when a decider recognises it.

**Theorem 15.10 (Decidable means recognisable both ways).**

A language $L$ is [decidable](#def-b3-computability-languages) if and only if $L$ and its complement $\overline{L}$ are both [recognisable](#def-b3-computability-languages).

**Proof.** If a [decider](#def-b3-computability-languages) $D$ recognises $L$, then $D$ recognises $L$, and $D$ with its answers swapped, still halting on every input, recognises $\overline{L}$. The converse runs the two recognisers side by side; [Exercise 15.7](#exo-b3-computability-7) completes it. ∎

## 15.5 Undecidability

**Definition 15.11 (Halting problem).**

The *halting problem* is the language $\mathit{HALT} = \{ \langle M, w \rangle : M \text{ halts on } w \}$.

$\mathit{HALT}$ is [recognisable](#def-b3-computability-languages): run the universal machine on $\langle M \rangle$ and $w$, and accept if it halts. It is not [decidable](#def-b3-computability-languages). Turing formulated the problem and proved it in the same paper.

**Theorem 15.12 (The halting problem is undecidable).**

No [Turing machine](#def-b3-computability-tm) decides $\mathit{HALT}$.

**Proof.** Suppose a [decider](#def-b3-computability-languages) $H$ answers whether $M$ halts on $w$. Build the machine $P$ that, on input $\langle M \rangle$, runs $H$ on $\langle M, \langle M \rangle \rangle$, loops for ever if $H$ answers yes, and halts if $H$ answers no. Run $P$ on $\langle P \rangle$. If $P$ halts on $\langle P \rangle$, $H$ answers yes on $\langle P, \langle P \rangle \rangle$, so $P$ loops: a contradiction. If $P$ does not halt, $H$ answers no, so $P$ halts: a contradiction again. So $H$ does not exist. ∎

The machines $M_0, M_1, \ldots$ against their [encodings](#def-b3-computability-universal) form a table whose entry $(i, j)$ says whether $M_i$ halts on $\langle M_j \rangle$; $P$ is built to disagree with the diagonal, exactly as the set $D$ of [Theorem 15.1](#thm-b3-computability-uncountable) does. `diagonal.py` runs the construction against four candidate [deciders](#def-b3-computability-languages): each is wrong about the program built from it.

![The diagonal argument as a table. The entries are invented for the picture.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computability/fig-dbcf82ad1841.svg)

*The diagonal argument as a table. The entries are invented for the picture.*

```python
def make_paradox(halts):
    def paradox(f):
        if halts(f, f):  # the decider says f(f) halts: then loop for ever
            while True:
                pass
        return "done"  # the decider says it loops: then halt at once
    return paradox


CANDIDATES = {
    "always yes": lambda f, x: True,
    "always no": lambda f, x: False,
    "no 'while' in the source": lambda f, x: "while" not in inspect.getsource(f),
    "short source": lambda f, x: len(inspect.getsource(f)) < 400,
}
```

***Listing 15.6.** The paradox built from a claimed [decider](#def-b3-computability-languages), and four candidate [deciders](#def-b3-computability-languages). code/bachelor-3/15-computability/listings/diagonal.py*

```
$ python diagonal.py
always yes                 says paradox(paradox) halts; it is still running
always no                  says paradox(paradox) loops; it halted
no 'while' in the source   says paradox(paradox) loops; it halted
short source               says paradox(paradox) halts; it is still running
(budget: 100,000 Python lines)
```

***Output 15.5.** Each candidate is wrong on its own paradox: when it says “halts” the paradox runs on, when it says “loops” the paradox halts.*

“Is still running” after 100,000 lines is not a proof that the program never halts; here the program’s text shows it, since the branch taken is `while True: pass`. A budget is how every practical tool meets the theorem: it answers “halts”, “loops” for the cases it can prove, and “don’t know” after its budget.

### 15.5.1 Reductions

Once one problem is known undecidable, others follow by translating questions.

**Definition 15.13 (Many-one reduction).**

A *many-one reduction* from a language $A$ to a language $B$ is a computable function $f$ such that $x \in A$ if and only if $f(x) \in B$, for every word $x$. We write $A \le_m B$.

**Theorem 15.14 (Reductions transfer undecidability).**

If $A \le_m B$ and $B$ is [decidable](#def-b3-computability-languages), then $A$ is [decidable](#def-b3-computability-languages). So if $A \le_m B$ and $A$ is undecidable, $B$ is undecidable.

**Proof.** To decide whether $x \in A$, compute $f(x)$ and run the [decider](#def-b3-computability-languages) of $B$ on it; both steps halt, and the answer is right because $x \in A \iff f(x) \in B$. ∎

Take $B = E = \{ \langle N \rangle : N \text{ accepts the empty word} \}$. Given $\langle M, w \rangle$, build $M_w$: it erases its input, writes $w$, returns to its first letter and runs $M$, accepting wherever $M$ halts. Then $M_w$ accepts the empty word, and in fact every word, if and only if $M$ halts on $w$. The map $\langle M, w \rangle \mapsto \langle M_w \rangle$ is computable; `reductions.py` computes it.

![A reduction from HALT to E: a decider for E would decide halting.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-computability/fig-d0e6c4331fe0.svg)

*A reduction from $\mathit{HALT}$ to $E$: a [decider](#def-b3-computability-languages) for $E$ would decide halting.*

```python
def reduce(delta, w, alphabet="01"):
    tape = alphabet + B
    m = {("erase", s): ("erase", B, "R") for s in alphabet}  # wipe any input
    m[("erase", B)] = ("w0", B, "S")
    for i, c in enumerate(w):  # write w, one state per letter
        m[(f"w{i}", B)] = (f"w{i + 1}", c, "R")
    m[(f"w{len(w)}", B)] = ("b0", B, "L")
    for j in range(len(w)):  # walk back to the first letter of w
        for s in tape:
            m[(f"b{j}", s)] = (f"b{j + 1}", s, "L" if j + 1 < len(w) else "S")
    for s in tape:
        m[(f"b{len(w)}", s)] = (("M", "q0"), s, "S")
    states = {q for q, _ in delta} | {r for r, _, _ in delta.values()}
    for q in states:  # M's transitions, and "accept" wherever M halts
        for s in tape:
            r = delta.get((q, s))
            m[(("M", q), s)] = (("M", r[0]), r[1], r[2]) if r else ("accept", s, "S")
    return m
```

***Listing 15.7.** The reduction $\langle M, w \rangle \mapsto \langle M_w \rangle$, as a transformation of transition tables. code/bachelor-3/15-computability/listings/reductions.py*

```
$ python reductions.py
M_w accepts the empty word / the word 0110, within 10,000 steps:
  M = INCREMENT, w = 1011: 32 transitions, [True, True]
  M = RUN_RIGHT, w = 1: 14 transitions, [False, False]
```

***Output 15.6.** $M_w$ accepts every word when $M$ halts on $w$, and none when it does not.*

So $E$ is undecidable. So is the emptiness problem, whether $L(N) = \varnothing$: $L(M_w)$ is empty exactly when $M$ does not halt on $w$, and a [decider](#def-b3-computability-languages) for emptiness, with its answer swapped, would decide halting. And so is equivalence, whether $L(N_1) = L(N_2)$: taking $N_2$ a machine that accepts nothing turns it into emptiness. These are all questions about what a machine accepts; one theorem settles them all.

**Definition 15.15 (Semantic property, non-trivial property).**

A property of [Turing machines](#def-b3-computability-tm) is *semantic* when it depends only on the language a machine recognises: two machines with the same language both have it or both lack it. It is *non-trivial* when some machine has it and some machine lacks it.

**Theorem 15.16 (Rice’s theorem).**

Every [non-trivial](#def-b3-computability-rice) [semantic property](#def-b3-computability-rice) of [Turing machines](#def-b3-computability-tm) is undecidable.

**Proof.** Let $\Pi$ be one. Suppose first that the machines whose language is empty lack $\Pi$, and let $K$ be a machine that has it. Given $\langle M, w \rangle$, build $N$: on input $x$, run $M$ on $w$; if that halts, run $K$ on $x$ and answer as $K$. If $M$ halts on $w$, $L(N) = L(K)$, so $N$ has $\Pi$; if not, $L(N) = \varnothing$, so $N$ lacks $\Pi$. The map $\langle M, w \rangle \mapsto \langle N \rangle$ is computable, so $\mathit{HALT} \le_m \Pi$, and $\Pi$ is undecidable by [Theorem 15.14](#thm-b3-computability-reduction). The other case, where the empty language has $\Pi$, is [Exercise 15.10](#exo-b3-computability-10). ∎

H. G. Rice published it in 1953. It covers “accepts the empty word”, “recognises a finite language”, “recognises a regular language”, “recognises the same language as this other machine”. It says nothing about properties of the machine’s text, such as “has at most five states”, which is [decidable](#def-b3-computability-languages), or “halts within 1,000 steps on the empty word”, [decidable](#def-b3-computability-languages) too, by running it.

**Definition 15.17 (Post correspondence problem).**

An instance of the *Post correspondence problem* is a finite list of tiles $(t_1, b_1), \ldots, (t_k, b_k)$, pairs of words; it asks whether some non-empty sequence of indices $i_1, \ldots, i_m$, with repetitions allowed, gives $t_{i_1} \cdots t_{i_m} = b_{i_1} \cdots b_{i_m}$.

The tiles $(a, baa)$, $(ab, aa)$, $(bba, bb)$ have the match 3, 2, 3, 1: both rows read `bbaabbbaa`. Emil Post introduced the problem in 1946 and proved it undecidable. The usual proof builds, from a machine and an input, a set of tiles whose matches spell out the machine’s run, so that a match exists if and only if the machine accepts. The problem mentions no machine at all, which makes it a convenient starting point for reductions to problems on words and grammars.

### 15.5.2 The busy beaver

**Definition 15.18 (Busy beaver function).**

Among the [Turing machines](#def-b3-computability-tm) with $n$ states, a halting state and the symbols 0 and 1, started on a tape of 0s, consider those that halt. The *busy beaver function* $S(n)$ is the largest number of steps one of them takes, the halting step included; $\Sigma(n)$ is the largest number of 1s one of them leaves.

Tibor Radó defined it in 1962, as one of the simplest functions no program computes.

For small $n$ a program can still find its values: enumerate every machine and run each one for a while.

```python
def run(machine, cap=CAP):
    """Steps and number of 1s if the machine halts within cap steps, else None."""
    tape, head, state = {}, 0, 0
    for step in range(1, cap + 1):
        write, move, state = machine[2 * state + tape.get(head, 0)]
        tape[head] = write
        head += move
        if state == "H":
            return step, sum(tape.values())
    return None


def busy_beaver(n):
    actions = list(product((0, 1), (-1, 1), [*range(n), "H"]))
    halting, best_s, best_sigma, champion = 0, 0, 0, None
    for machine in product(actions, repeat=2 * n):
        result = run(machine)
        if result is None:
            continue
        halting += 1
        best_s = max(best_s, result[0])
        if result[1] > best_sigma:
            best_sigma, champion = result[1], machine
    return len(actions) ** (2 * n), halting, best_s, best_sigma, champion
```

***Listing 15.8.** Every $n$-state machine, run for at most `CAP` steps from the blank tape. code/bachelor-3/15-computability/listings/busy_beaver.py*

```
$ python busy_beaver.py
n = 1: 64 machines, 32 halt within 100 steps; S(1) = 1, Sigma(1) = 1
n = 2: 20,736 machines, 9,784 halt within 100 steps; S(2) = 6, Sigma(2) = 4
a Sigma(2) champion: 1LB 1RB 1RA 1LH
```

***Output 15.7.** All one- and two-state machines: $S(2) = 6$ and $\Sigma(2) = 4$, as the weekend problem confirms.*

**Theorem 15.19 (SSS is not computable).**

No [Turing machine](#def-b3-computability-tm) computes $n \mapsto S(n)$.

**Proof.** If one did, the following would decide whether a two-symbol machine $M$ with $n$ states halts on the blank tape: compute $S(n)$, run $M$ for $S(n)$ steps, and answer “halts” if it has halted. A machine that is still running then never halts, since a halting one would have taken at most $S(n)$ steps. But halting on the blank tape is undecidable: the map $\langle M, w \rangle \mapsto \langle M_w \rangle$ of [Listing 15.7](#lst-b3-computability-reduction) reduces $\mathit{HALT}$ to it, once the symbols of $M_w$ are coded in binary, which costs states but not halting. ∎

**Facts as of 2026.**

Five values of $S$ are known: $S(1) = 1$, $S(2) = 6$, $S(3) = 21$, $S(4) = 107$ and $S(5) = 47{,}176{,}870$, with $\Sigma(5) = 4{,}098$. The fifth was settled by the online bbchallenge collaboration, whose proof, checked by the Coq proof assistant, enumerated 181,385,789 machines; the proof appeared in the spring of 2024 and the paper in 2025. For six states only lower bounds are known, beyond any number that can be written out.

## 15.6 Exercises

**Exercise 15.1 ★.**

Run the palindrome machine of [Listing 15.2](#lst-b3-computability-machines) on `aba` for five steps, writing the six [configurations](#def-b3-computability-tm) from `[q0]aba`.

**Solution of Exercise 15.1.**

`[q0]aba`, `_[has_a]ba`, `_b[has_a]a`, `_ba[has_a]_`, `_b[end_a]a_`, `_[back]b__`. The machine has erased the first `a`, walked to the end, found an `a` there, erased it, and is walking back. Five more steps accept: the `b` left alone is erased and the machine finds blanks on both sides.

**Exercise 15.2 ★.**

[Decidable](#def-b3-computability-languages), [recognisable](#def-b3-computability-languages) but not [decidable](#def-b3-computability-languages), or not even [recognisable](#def-b3-computability-languages)? (a) The [encodings](#def-b3-computability-universal) of machines with at most five states. (b) $E$, the machines that accept the empty word. (c) The complement of $E$. (d) The pairs $\langle M, w \rangle$ such that $M$ halts on $w$ within 1,000 steps.

**Solution of Exercise 15.2.**

(a) [Decidable](#def-b3-computability-languages): read the [encoding](#def-b3-computability-universal) and count the states. (b) [Recognisable](#def-b3-computability-languages), since a machine can run $N$ on the empty word through the universal machine and accept if it accepts; not [decidable](#def-b3-computability-languages), by the reduction of the chapter. (c) Not [recognisable](#def-b3-computability-languages): if it were, $E$ and its complement would both be [recognisable](#def-b3-computability-languages), and $E$ would be [decidable](#def-b3-computability-languages) by [Theorem 15.10](#thm-b3-computability-complement). (d) [Decidable](#def-b3-computability-languages): run $M$ on $w$ for at most 1,000 steps.

**Exercise 15.3 ★.**

With the conventions of `utm.py`, the symbols of the adder are `+`, `1`, `_`, numbered 1, 2, 3, and its states `q0`, `done`, `last`. Write the code of the transition $(\mathtt{q0}, \mathtt{+}) \to (\mathtt{q0}, \mathtt{1}, R)$, and that of $(\mathtt{last}, \mathtt{1}) \to (\mathtt{done}, \mathtt{\_}, S)$.

**Solution of Exercise 15.3.**

$(\mathtt{q0}, \mathtt{+}) \to (\mathtt{q0}, \mathtt{1}, R)$ is the numbers 1, 1, 1, 2, 2: `10101011011`. $(\mathtt{last}, \mathtt{1}) \to (\mathtt{done}, \mathtt{\_}, S)$ is 3, 2, 2, 3, 3: `11101101101110111`. The whole adder has 58 characters (`utm.encode(ADD)`).

**Exercise 15.4 ★.**

Predict, without running them: the tape and the number of steps of the increment machine on `1111`; the tape of the adder on `1+1`; the number of steps of the palindrome machine on `aa`.

**Solution of Exercise 15.4.**

The increment walks right over four digits (4 steps), steps back onto the blank’s left (1), turns four 1s into 0s (4) and writes a 1 on the blank (1): tape `10000`, 10 steps. The adder on `1+1` turns `+` into 1 and erases the last 1: `11`. The palindrome machine on `aa` erases the first `a`, passes the second, finds the blank, steps back, erases the second, steps back, and finds an empty word: 6 steps, $(2 + 1)(2 + 2)/2$ (`test_exercise_4_predictions`).

**Exercise 15.5 ★★.**

`exercises/ex5_increment.py` gives a binary increment that turns `111` into `000`. Find the missing transition and fix it; the test checks every number below 256.

**Solution of Exercise 15.5.**

On `111` the carry turns all three 1s into 0s and reaches the blank left of the number, where no transition applies: the machine halts with `000`. The missing transition is `("carry", B): ("done", "1", "S")`, a new leading 1 (`exercises/ex5_increment.py`).

**Exercise 15.6 ★★.**

Write a [Turing machine](#def-b3-computability-tm) for the simulator that accepts exactly the words $a^n b^n$, $n \ge 0$, over $\{a, b\}$. It is tested on every word of length at most 8.

**Solution of Exercise 15.6.**

`exercises/ex6_anbn.py`: each round crosses off the leftmost `a` as `X`, walks right over `a`s and `Y`s to the first `b`, crosses it off as `Y`, and walks back to the last `X`. When the next letter is a `Y` instead of an `a`, every `a` is crossed off, and the machine accepts if only `Y`s follow. A `b` before an `a`, an `a` after the `b`s, or a missing `b` leaves the machine with no transition, and it rejects.

**Exercise 15.7 ★★.**

Prove the converse in [Theorem 15.10](#thm-b3-computability-complement): if $L$ and $\overline{L}$ are [recognisable](#def-b3-computability-languages), $L$ is [decidable](#def-b3-computability-languages). (Run the two recognisers one step each in turn.)

**Solution of Exercise 15.7.**

Let $R_1$ recognise $L$ and $R_2$ recognise $\overline{L}$. The [decider](#def-b3-computability-languages) $D$, on $w$, simulates one step of $R_1$ on $w$, then one step of $R_2$, and so on, keeping both [configurations](#def-b3-computability-tm) on its tape (a two-tape machine, then one tape by [Theorem 15.4](#thm-b3-computability-multitape)). If $R_1$ accepts, $D$ accepts; if $R_2$ accepts, $D$ rejects. Every word is in $L$ or in $\overline{L}$, so one of the two accepts after finitely many steps, and $D$ halts. It never answers wrongly, since $R_1$ accepts only words of $L$ and $R_2$ only words of $\overline{L}$.

**Exercise 15.8 ★★.**

Prove that $\mathit{TOTAL} = \{ \langle M \rangle : M \text{ halts on every input} \}$ is undecidable, by a reduction from $\mathit{HALT}$. Is it a case of Rice’s theorem as stated?

**Solution of Exercise 15.8.**

The map $\langle M, w \rangle \mapsto \langle M_w \rangle$ of the chapter works: $M_w$ ignores its input and runs $M$ on $w$, so it halts on every input if $M$ halts on $w$ and on none otherwise. Hence $\mathit{HALT} \le_m \mathit{TOTAL}$, and $\mathit{TOTAL}$ is undecidable. It is not a case of Rice’s theorem as stated: halting on every input is not a property of the language accepted, since a machine that rejects by halting and one that rejects by looping can accept the same words.

**Exercise 15.9 ★★.**

Explain the two columns of [Output 15.2](#out-b3-computability-multitape): why the two-tape machine takes exactly $3n + 3$ steps on a palindrome of length $n$, and why the one-tape machine takes $(n + 1)(n + 2)/2$.

**Solution of Exercise 15.9.**

Two tapes: $n$ steps copy, one step at the end of the word, $n$ steps rewind and one more step back onto the first letter, then $n$ comparisons and one step to accept: $3n + 3$. One tape: each round on a word of length $m$ walks right over $m$ cells and back over $m - 1$, plus the steps onto the ends, about $2m$ steps, and removes two letters; summing over $m = n, n - 2, \ldots$ gives $(n + 1)(n + 2)/2$, quadratic as [Theorem 15.4](#thm-b3-computability-multitape) allows (`test_palindromes_one_and_two_tapes` checks both formulas for every palindrome of length at most 8).

**Exercise 15.10 ★★★.**

Finish the proof of Rice’s theorem: the case where the machines whose language is empty have the property.

**Solution of Exercise 15.10.**

If the machines with empty language have $\Pi$, then $\overline{\Pi}$, the property of lacking $\Pi$, is [semantic](#def-b3-computability-rice) and [non-trivial](#def-b3-computability-rice), and machines with the empty language lack it. By the case proved in the chapter, $\overline{\Pi}$ is undecidable. A [decider](#def-b3-computability-languages) for $\Pi$, with its answers swapped, would decide $\overline{\Pi}$; so $\Pi$ is undecidable too.

**Exercise 15.11 ★★★.**

Let $f$ be any total computable function on natural numbers. Prove that $S(n) > f(n)$ for all large enough $n$. (Build, for each $n$, a machine of $n + c$ states, $c$ fixed, that writes $n$ in unary and then writes a value of $f$ in unary.)

**Solution of Exercise 15.11.**

Facts used: $f \ge 0$ is total and computable, so $g(n) = f(2n) + f(2n + 1) + 1$ is too, and a two-symbol machine computes it from $n$ written in unary, with some number $c$ of states, leaving $g(n)$ 1s; writing $n$ 1s on the blank tape takes $n$ states, one per 1; $S$ is increasing (problem, question 18).

The machine $B_n$ writes $n$ 1s, then runs the machine for $g$. It halts, has $n + c$ states, and takes at least $g(n)$ steps, since it leaves $g(n)$ 1s and writes one per step at most. So $S(n + c) \ge g(n)$. For $n \ge c$, $n + c \le 2n$, hence $S(2n + 1) \ge S(2n) \ge S(n + c) \ge g(n)$, which exceeds both $f(2n)$ and $f(2n + 1)$. So $S(m) > f(m)$ for every $m \ge 2c$. In particular $S \ne f$ for every computable $f$: a second proof of [Theorem 15.19](#thm-b3-computability-busy-beaver).

**Exercise 15.12 ★★★.**

With only `zero`, `succ`, `proj`, `compose`, `primrec` and the functions they already build, define `pred` (the predecessor, 0 for 0), `monus` ($x \mathbin{\dot-} y$, the difference cut at 0) and `div` (integer division for $y > 0$). The test compares them with Python’s operators.

**Solution of Exercise 15.12.**

`exercises/ex12_primrec.py`. `pred` is primitive recursion with base 0 and step “the previous $n$”. `monus` recurses on the subtracted number, applying `pred` once per step, then swaps the arguments. A test for zero, $1 \mathbin{\dot-} x$, and equality, zero of $(x \mathbin{\dot-} y) + (y \mathbin{\dot-} x)$, give the remainder: count up and wrap to 0 when the count reaches $y$. `div` adds 1 each time the remainder of the next number is 0 (`test_exercise_12_primitive_recursive`).

## 15.7 Weekend problem

**Problem 15.1.**

Weekend problem — The busy beaver

This problem counts the two-state machines, runs them all, finds the champion of [Output 15.7](#out-b3-computability-busy) by hand, and proves that no program computes the [busy beaver function](#def-b3-computability-busy-beaver). Machines are written as in `busy_beaver.py`: `1LB` means write 1, move left, go to state B; the transitions are listed for A0, A1, B0, B1.

**Part I — How many machines.**

1. How many actions can one transition take, with $n$ states and a halting state? How many machines with $n$ states are there?
2. Check the counts 64 and 20,736 of [Output 15.7](#out-b3-computability-busy) . How many three-state machines are there?
3. Why do exactly 32 of the 64 one-state machines halt, and why do they all halt after one step?
4. The five-state proof enumerated 181,385,789 machines. How many five-state machines does the formula of question 1 give? Why can a proof enumerate far fewer?
5. Two machines that differ only by swapping left and right take the same number of steps. Why?

**Part II — Running them all.**

6. Why does `busy_beaver.py` need a step cap at all?
7. What can the cap make the program get wrong, and in which direction?
8. 9,784 machines halted within 100 steps. Why is it safe to say the other 10,952 never halt, given that $S(2) = 6$ is proved?
9. Without knowing $S(2)$ , what would a cap of 100 prove about $S(2)$ ?
10. The test runs every two-state machine for 1,000 steps and finds none that halts after step 6. Why is that evidence, and not a proof?
11. Give a simple argument proving that a machine never halts when it has no transition to H that can ever be taken from the states it visits.

**Part III — The champion.**

12. Run the champion `1LB 1RB 1RA 1LH` by hand from the blank tape, writing the [configuration](#def-b3-computability-tm) after each step. How many steps, how many 1s?
13. Why does its last transition write a 1 rather than a 0?
14. Write its mirror image. Why does it have the same counts?
15. The program finds 4 machines that leave four 1s. Which are they?
16. It finds 40 machines that take six steps. Why many more than for $\Sigma$ ?
17. Can a machine take $S(n)$ steps without leaving $\Sigma(n)$ 1s? Use the counts above.

**Part IV — No program computes $S$.**

18. Prove $S(n + 1) > S(n)$ for every $n$ .
19. Prove, as in [Theorem 15.19](#thm-b3-computability-busy-beaver) , that a program computing $S$ would decide halting on the blank tape.
20. Why does that contradict [Theorem 15.12](#thm-b3-computability-halting) ?
21. From [Exercise 15.11](#exo-b3-computability-11) : why does a function that grows faster than every computable function fail to be computable?
22. Each known value of $S$ needed a proof that every other machine never halts. Why does no single program give those proofs for every $n$ ?
23. What does a proof checked by a proof assistant add, for a result that rests on 181 million cases?
24. Sum up what was computed, and what cannot be.

**Solution of Problem 15.1.**

**1.** Write 0 or 1, move left or right, go to one of $n + 1$ states: $4(n + 1)$ actions. Each of the $2n$ pairs (state, symbol) gets one: $(4(n + 1))^{2n}$ machines.

**2.** $8^2 = 64$ and $12^4 = 20{,}736$. For three states, $16^6 = 16{,}777{,}216$.

**3.** From the blank tape the only transition ever used is A0. Of its 8 actions, 4 go to H and 4 back to A: those 4 times the 8 choices for the unused A1 make 32 halting machines, each after one step. The others repeat A0 for ever.

**4.** $24^{10} \approx 6.3 \times 10^{13}$. A proof needs one representative per class of equivalent machines: it fixes the first move, ignores mirror images, and builds the table only as far as the run uses it, filling a transition the first time it is reached; unused transitions never multiply the count.

**5.** Every run is the mirror image of the other’s: the tape is reversed, and the steps and the 1s are the same.

**6.** Some machines never halt, and no program can tell in general which: without a cap the enumeration would never end.

**7.** It can count as non-halting a machine that halts after the cap, and so underestimate $S$ and $\Sigma$; it never overestimates them.

**8.** Every halting two-state machine halts within $S(2) = 6$ steps, so one that is still running at step 100 never halts.

**9.** Only $S(2) \ge 6$: some machine might halt after step 100.

**10.** A machine could halt after step 1,000; a larger cap pushes the doubt back without removing it. The proof of $S(2) = 6$ shows for each remaining machine why it never halts.

**11.** From the blank tape, consider the states the machine can reach by following the transitions from A. If none of them has a transition to H, then at every step the machine is in one of these states, and some transition applies (every pair has one), so it never halts.

**12.** `[A]0`, `[B]01`, `1[A]1`, `11[B]0`, `111[A]0`, `11[B]11`, `1[H]111`, with 0 for blank: 6 steps, four 1s.

**13.** The halting transition is B1: it reads a 1. Writing 1 keeps it; writing 0 would erase it and leave three 1s.

**14.** `1RB 1LB 1LA 1RH`: every move reversed, the same run reflected.

**15.** The champion and its mirror, each with the halting move left or right: the last move does not change the tape.

**16.** The steps do not depend on what the halting transition writes, nor on its move; and several different runs of six steps exist, leaving fewer 1s.

**17.** Yes: 40 machines take six steps, only 4 leave four 1s.

**18.** Take a machine with $n$ states that takes $S(n)$ steps. Replace its halting transition by one to a new state, which then halts in one more step: $n + 1$ states, $S(n) + 1$ steps.

**19.** Given $M$ with $n$ states, compute $S(n)$ and run $M$ for $S(n)$ steps from the blank tape. If it has not halted, it never will, since a halting machine of $n$ states takes at most $S(n)$ steps.

**20.** Halting on the blank tape is undecidable: $\mathit{HALT}$ reduces to it by $\langle M, w \rangle \mapsto \langle M_w \rangle$, $M_w$ written with two symbols.

**21.** If it were computable, it would exceed itself at all large $n$.

**22.** A single program giving them would compute $S$: from the proofs, enumerate the machines, discard those proved non-halting, and run the others to the end.

**23.** A computer counted the 181 million cases; the proof assistant checks that the program which did so, and the argument it implements, are correct, rather than asking readers to trust the code.

**24.** An enumeration with a cap gives lower bounds for $S(n)$ and $\Sigma(n)$, and a proof that the remaining machines never halt makes them exact: $S(2) = 6$ and $\Sigma(2) = 4$ by the chapter’s program, $S(5) = 47{,}176{,}870$ by a collaboration. No program computes $S(n)$ for every $n$, since that program would decide halting, and $S$ outgrows every computable function.
