কম্পিউটার বিজ্ঞান · বই 5 · স্নাতক তৃতীয় বর্ষ

University Computer Science — Year 3

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 3 · স্নাতক তৃতীয় বর্ষ

15Turing 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. A simulator of thirty lines runs three machines; a second tape changes the speed but not the power; primitive and μ\mu-recursive functions 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 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 showed that no program decides, for every program and input, whether that program halts: from a claimed decider it built a program that does the opposite of what the decider 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: P0,P1,P2,…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 A0,A1,A2,…A_0, A_1, A_2, \ldots. The set D={n:n∉An}D = \{n : n \notin A_n\} differs from each AnA_n on the number nn, 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] vu\,[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.

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}\{a, b\}, which erases the first letter, remembers it in its state, and checks it against the last; and a unary adder (machines.py).

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 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. Left: the Pilot ACE, a cut-down version of Turing’s design (Science Museum, London). Right: the increment machine of  after two steps.
Left: the Pilot ACE, a cut-down version of Turing’s design (Science Museum, London). Right: the increment machine of Output 15.1 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: 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 kk tapes reads the kk symbols under its kk heads; its transition function gives the new state, the kk symbols written and the kk moves. The input starts on the first tape; the others start blank.

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 nn: about n2/2n^2/2 with one tape, 3n+33n + 3 with two.

The one-tape machine walks the whole word for each pair of letters it crosses off: (n+1)(n+2)/2(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 kk)

For every kk-tape Turing machine there is a one-tape machine that halts on the same inputs with the same output; if the first takes t≥nt \ge n steps on an input of length nn, the second takes O(t2)O(t^2) steps.

Proof idea. Store the kk tapes on one, side by side: cell ii of the single tape holds a tuple of kk symbols, cell ii of each tape, each marked if a head is there (the alphabet of tuples is finite). One step of the kk-tape machine becomes a sweep: left to right to read the kk marked symbols into the state, then back to write and move the marks. After tt steps the used part of the tape has at most n+t≤2tn + t \le 2t cells, so each sweep costs O(t)O(t) steps and the whole run O(t2)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 studies, but it changes nothing about what can be computed at all.

15.3 The Church–Turing thesis

The Turing machine 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. 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↦n+1n \mapsto n + 1 and the projections (x1,…,xk)↦xi(x_1, \ldots, x_k) \mapsto x_i by composition and by primitive recursion: h(0,y⃗)=g(y⃗)h(0, \vec y) = g(\vec y) and h(n+1,y⃗)=s(n,h(n,y⃗),y⃗)h(n + 1, \vec y) = s(n, h(n, \vec y), \vec y). The μ\mu-recursive functions also allow minimisation: μp(y⃗)\mu p(\vec y) is the least nn with p(n,y⃗)=0p(n, \vec y) = 0, undefined if there is none. The Ackermann function is A(0,n)=n+1A(0, n) = n + 1, A(m+1,0)=A(m,1)A(m + 1, 0) = A(m, 1), A(m+1,n+1)=A(m,A(m+1,n))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.

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+2n + 2, 2n+32n + 3, 2n+3−32^{n + 3} - 3.

Every primitive recursive function 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 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,533A(4, 1) = 65{,}533, and A(4,2)=265536−3A(4, 2) = 2^{65536} - 3 has 19,729 digits.

Theorem 15.6 (The models agree)

The total functions computable by a Turing machine, the total μ\mu-recursive functions, 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 can carry out composition, a bounded loop and an unbounded search on numbers written on its tape. Conversely, a configuration of a Turing machine can be coded as a number, one step is a primitive recursive function 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.

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: 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 exists.

15.4 A universal machine

A Turing machine 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 maps each machine MM to a word ⟨M⟩\langle M \rangle over a fixed alphabet, so that the table of MM can be computed back from it. A universal Turing machine UU takes ⟨M⟩\langle M \rangle and a word ww, and behaves as MM on ww: it halts if and only if MM halts, accepts if and only if MM accepts, and leaves MM’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.

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 a machine over {0,1,#}\{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, 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 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 LL is decidable if and only if LL and its complement L‾\overline{L} are both recognisable.

Proof. If a decider DD recognises LL, then DD recognises LL, and DD with its answers swapped, still halting on every input, recognises L‾\overline{L}. The converse runs the two recognisers side by side; Exercise 15.7 completes it. ∎

15.5 Undecidability

Definition 15.11 (Halting problem)

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

HALT\mathit{HALT} is recognisable: run the universal machine on ⟨M⟩\langle M \rangle and ww, and accept if it halts. It is not decidable. Turing formulated the problem and proved it in the same paper.

Theorem 15.12 (The halting problem is undecidable)

No Turing machine decides HALT\mathit{HALT}.

Proof. Suppose a decider HH answers whether MM halts on ww. Build the machine PP that, on input ⟨M⟩\langle M \rangle, runs HH on ⟨M,⟨M⟩⟩\langle M, \langle M \rangle \rangle, loops for ever if HH answers yes, and halts if HH answers no. Run PP on ⟨P⟩\langle P \rangle. If PP halts on ⟨P⟩\langle P \rangle, HH answers yes on ⟨P,⟨P⟩⟩\langle P, \langle P \rangle \rangle, so PP loops: a contradiction. If PP does not halt, HH answers no, so PP halts: a contradiction again. So HH does not exist. ∎

The machines M0,M1,…M_0, M_1, \ldots against their encodings form a table whose entry (i,j)(i, j) says whether MiM_i halts on ⟨Mj⟩\langle M_j \rangle; PP is built to disagree with the diagonal, exactly as the set DD of Theorem 15.1 does. diagonal.py runs the construction against four candidate deciders: each is wrong about the program built from it.

The diagonal argument as a table. The entries are invented for the picture.
The diagonal argument as a table. The entries are invented for the picture.
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, and four candidate deciders. 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 AA to a language BB is a computable function ff such that x∈Ax \in A if and only if f(x)∈Bf(x) \in B, for every word xx. We write A≤mBA \le_m B.

Theorem 15.14 (Reductions transfer undecidability)

If A≤mBA \le_m B and BB is decidable, then AA is decidable. So if A≤mBA \le_m B and AA is undecidable, BB is undecidable.

Proof. To decide whether x∈Ax \in A, compute f(x)f(x) and run the decider of BB on it; both steps halt, and the answer is right because x∈A  ⟺  f(x)∈Bx \in A \iff f(x) \in B. ∎

Take B=E={⟨N⟩:N accepts the empty word}B = E = \{ \langle N \rangle : N \text{ accepts the empty word} \}. Given ⟨M,w⟩\langle M, w \rangle, build MwM_w: it erases its input, writes ww, returns to its first letter and runs MM, accepting wherever MM halts. Then MwM_w accepts the empty word, and in fact every word, if and only if MM halts on ww. The map ⟨M,w⟩↦⟨Mw⟩\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.
A reduction from HALT\mathit{HALT} to EE: a decider for EE would decide halting.
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 ⟨M,w⟩↦⟨Mw⟩\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. MwM_w accepts every word when MM halts on ww, and none when it does not.

So EE is undecidable. So is the emptiness problem, whether L(N)=∅L(N) = \varnothing: L(Mw)L(M_w) is empty exactly when MM does not halt on ww, and a decider for emptiness, with its answer swapped, would decide halting. And so is equivalence, whether L(N1)=L(N2)L(N_1) = L(N_2): taking N2N_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 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 semantic property of Turing machines is undecidable.

Proof. Let Π\Pi be one. Suppose first that the machines whose language is empty lack Π\Pi, and let KK be a machine that has it. Given ⟨M,w⟩\langle M, w \rangle, build NN: on input xx, run MM on ww; if that halts, run KK on xx and answer as KK. If MM halts on ww, L(N)=L(K)L(N) = L(K), so NN has Π\Pi; if not, L(N)=∅L(N) = \varnothing, so NN lacks Π\Pi. The map ⟨M,w⟩↦⟨N⟩\langle M, w \rangle \mapsto \langle N \rangle is computable, so HALT≤mΠ\mathit{HALT} \le_m \Pi, and Π\Pi is undecidable by Theorem 15.14. The other case, where the empty language has Π\Pi, is Exercise 15.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, or “halts within 1,000 steps on the empty word”, decidable too, by running it.

Definition 15.17 (Post correspondence problem)

An instance of the Post correspondence problem is a finite list of tiles (t1,b1),…,(tk,bk)(t_1, b_1), \ldots, (t_k, b_k), pairs of words; it asks whether some non-empty sequence of indices i1,…,imi_1, \ldots, i_m, with repetitions allowed, gives ti1⋯tim=bi1⋯bimt_{i_1} \cdots t_{i_m} = b_{i_1} \cdots b_{i_m}.

The tiles (a,baa)(a, baa), (ab,aa)(ab, aa), (bba,bb)(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 with nn 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)S(n) is the largest number of steps one of them takes, the halting step included; Σ(n)\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 nn a program can still find its values: enumerate every machine and run each one for a while.

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 nn-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)=6S(2) = 6 and Σ(2)=4\Sigma(2) = 4, as the weekend problem confirms.

Theorem 15.19 (SS is not computable)

No Turing machine computes n↦S(n)n \mapsto S(n).

Proof. If one did, the following would decide whether a two-symbol machine MM with nn states halts on the blank tape: compute S(n)S(n), run MM for S(n)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)S(n) steps. But halting on the blank tape is undecidable: the map ⟨M,w⟩↦⟨Mw⟩\langle M, w \rangle \mapsto \langle M_w \rangle of Listing 15.7 reduces HALT\mathit{HALT} to it, once the symbols of MwM_w are coded in binary, which costs states but not halting. ∎

Facts as of 2026

Five values of SS are known: S(1)=1S(1) = 1, S(2)=6S(2) = 6, S(3)=21S(3) = 21, S(4)=107S(4) = 107 and S(5)=47,176,870S(5) = 47{,}176{,}870, with Σ(5)=4,098\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 on aba for five steps, writing the six configurations from [q0]aba.

Solution

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, recognisable but not decidable, or not even recognisable? (a) The encodings of machines with at most five states. (b) EE, the machines that accept the empty word. (c) The complement of EE. (d) The pairs ⟨M,w⟩\langle M, w \rangle such that MM halts on ww within 1,000 steps.

Solution

Solution of Exercise 15.2.

(a) Decidable: read the encoding and count the states. (b) Recognisable, since a machine can run NN on the empty word through the universal machine and accept if it accepts; not decidable, by the reduction of the chapter. (c) Not recognisable: if it were, EE and its complement would both be recognisable, and EE would be decidable by Theorem 15.10. (d) Decidable: run MM on ww 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 (q0,+)→(q0,1,R)(\mathtt{q0}, \mathtt{+}) \to (\mathtt{q0}, \mathtt{1}, R), and that of (last,1)→(done,_,S)(\mathtt{last}, \mathtt{1}) \to (\mathtt{done}, \mathtt{\_}, S).

Solution

Solution of Exercise 15.3.

(q0,+)→(q0,1,R)(\mathtt{q0}, \mathtt{+}) \to (\mathtt{q0}, \mathtt{1}, R) is the numbers 1, 1, 1, 2, 2: 10101011011. (last,1)→(done,_,S)(\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

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(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

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 for the simulator that accepts exactly the words anbna^n b^n, n≥0n \ge 0, over {a,b}\{a, b\}. It is tested on every word of length at most 8.

Solution

Solution of Exercise 15.6.

exercises/ex6_anbn.py: each round crosses off the leftmost a as X, walks right over as and Ys 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 Ys follow. A b before an a, an a after the bs, or a missing b leaves the machine with no transition, and it rejects.

Exercise 15.7 ★★

Prove the converse in Theorem 15.10: if LL and L‾\overline{L} are recognisable, LL is decidable. (Run the two recognisers one step each in turn.)

Solution

Solution of Exercise 15.7.

Let R1R_1 recognise LL and R2R_2 recognise L‾\overline{L}. The decider DD, on ww, simulates one step of R1R_1 on ww, then one step of R2R_2, and so on, keeping both configurations on its tape (a two-tape machine, then one tape by Theorem 15.4). If R1R_1 accepts, DD accepts; if R2R_2 accepts, DD rejects. Every word is in LL or in L‾\overline{L}, so one of the two accepts after finitely many steps, and DD halts. It never answers wrongly, since R1R_1 accepts only words of LL and R2R_2 only words of L‾\overline{L}.

Exercise 15.8 ★★

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

Solution

Solution of Exercise 15.8.

The map ⟨M,w⟩↦⟨Mw⟩\langle M, w \rangle \mapsto \langle M_w \rangle of the chapter works: MwM_w ignores its input and runs MM on ww, so it halts on every input if MM halts on ww and on none otherwise. Hence HALT≤mTOTAL\mathit{HALT} \le_m \mathit{TOTAL}, and TOTAL\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: why the two-tape machine takes exactly 3n+33n + 3 steps on a palindrome of length nn, and why the one-tape machine takes (n+1)(n+2)/2(n + 1)(n + 2)/2.

Solution

Solution of Exercise 15.9.

Two tapes: nn steps copy, one step at the end of the word, nn steps rewind and one more step back onto the first letter, then nn comparisons and one step to accept: 3n+33n + 3. One tape: each round on a word of length mm walks right over mm cells and back over m−1m - 1, plus the steps onto the ends, about 2m2m steps, and removes two letters; summing over m=n,n−2,…m = n, n - 2, \ldots gives (n+1)(n+2)/2(n + 1)(n + 2)/2, quadratic as Theorem 15.4 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

Solution of Exercise 15.10.

If the machines with empty language have Π\Pi, then Π‾\overline{\Pi}, the property of lacking Π\Pi, is semantic and non-trivial, and machines with the empty language lack it. By the case proved in the chapter, Π‾\overline{\Pi} is undecidable. A decider for Π\Pi, with its answers swapped, would decide Π‾\overline{\Pi}; so Π\Pi is undecidable too.

Exercise 15.11 ★★★

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

Solution

Solution of Exercise 15.11.

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

The machine BnB_n writes nn 1s, then runs the machine for gg. It halts, has n+cn + c states, and takes at least g(n)g(n) steps, since it leaves g(n)g(n) 1s and writes one per step at most. So S(n+c)≥g(n)S(n + c) \ge g(n). For n≥cn \ge c, n+c≤2nn + c \le 2n, hence S(2n+1)≥S(2n)≥S(n+c)≥g(n)S(2n + 1) \ge S(2n) \ge S(n + c) \ge g(n), which exceeds both f(2n)f(2n) and f(2n+1)f(2n + 1). So S(m)>f(m)S(m) > f(m) for every m≥2cm \ge 2c. In particular S≠fS \ne f for every computable ff: a second proof of Theorem 15.19.

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−˙yx \mathbin{\dot-} y, the difference cut at 0) and div (integer division for y>0y > 0). The test compares them with Python’s operators.

Solution

Solution of Exercise 15.12.

exercises/ex12_primrec.py. pred is primitive recursion with base 0 and step “the previous nn”. monus recurses on the subtracted number, applying pred once per step, then swaps the arguments. A test for zero, 1−˙x1 \mathbin{\dot-} x, and equality, zero of (x−˙y)+(y−˙x)(x \mathbin{\dot-} y) + (y \mathbin{\dot-} x), give the remainder: count up and wrap to 0 when the count reaches yy. 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 by hand, and proves that no program computes the busy beaver function. 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 nn states and a halting state? How many machines with nn states are there?
  2. Check the counts 64 and 20,736 of Output 15.7. 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.

  1. Why does busy_beaver.py need a step cap at all?
  2. What can the cap make the program get wrong, and in which direction?
  3. 9,784 machines halted within 100 steps. Why is it safe to say the other 10,952 never halt, given that S(2)=6S(2) = 6 is proved?
  4. Without knowing S(2)S(2), what would a cap of 100 prove about S(2)S(2)?
  5. 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?
  6. 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.

  1. Run the champion 1LB 1RB 1RA 1LH by hand from the blank tape, writing the configuration after each step. How many steps, how many 1s?
  2. Why does its last transition write a 1 rather than a 0?
  3. Write its mirror image. Why does it have the same counts?
  4. The program finds 4 machines that leave four 1s. Which are they?
  5. It finds 40 machines that take six steps. Why many more than for Σ\Sigma?
  6. Can a machine take S(n)S(n) steps without leaving Σ(n)\Sigma(n) 1s? Use the counts above.

Part IV — No program computes SS.

  1. Prove S(n+1)>S(n)S(n + 1) > S(n) for every nn.
  2. Prove, as in Theorem 15.19, that a program computing SS would decide halting on the blank tape.
  3. Why does that contradict Theorem 15.12?
  4. From Exercise 15.11: why does a function that grows faster than every computable function fail to be computable?
  5. Each known value of SS needed a proof that every other machine never halts. Why does no single program give those proofs for every nn?
  6. What does a proof checked by a proof assistant add, for a result that rests on 181 million cases?
  7. Sum up what was computed, and what cannot be.
Solution

Solution of Problem 15.1.

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

2. 82=648^2 = 64 and 124=20,73612^4 = 20{,}736. For three states, 166=16,777,21616^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. 2410≈6.3×101324^{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 SS and Σ\Sigma; it never overestimates them.

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

9. Only S(2)≥6S(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)=6S(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 nn states that takes S(n)S(n) steps. Replace its halting transition by one to a new state, which then halts in one more step: n+1n + 1 states, S(n)+1S(n) + 1 steps.

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

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

21. If it were computable, it would exceed itself at all large nn.

22. A single program giving them would compute SS: 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)S(n) and Σ(n)\Sigma(n), and a proof that the remaining machines never halt makes them exact: S(2)=6S(2) = 6 and Σ(2)=4\Sigma(2) = 4 by the chapter’s program, S(5)=47,176,870S(5) = 47{,}176{,}870 by a collaboration. No program computes S(n)S(n) for every nn, since that program would decide halting, and SS outgrows every computable function.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো