---
title: "What Programs Cannot Do: The Halting Problem"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 34
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/34-what-programs-cannot-do-the-halting-problem
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 34 — What Programs Cannot Do: The Halting Problem

Every programmer has waited in front of a program that does not answer, wondering whether it is still computing or caught in a loop for ever. A tool that read any program, with its input, and said for certain whether it would ever stop would catch a whole family of bugs before they happen. Such a tool cannot exist. Not because nobody has been clever enough yet: there is a proof, short enough for a page, that every attempt must fail on some program.

The proof rests on one idea that this book has used since the toy machine: a program is data. A program can read another program, run it, or change it, and nothing prevents a program from reading itself. The chapter starts there, proves the theorem, then measures what it leaves possible, on a machine small enough to be decided completely.

**You already know.**

A von Neumann machine keeps the program and its data in the same memory, and [assembly language](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) names the instructions of the processor (chapter [13](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#ch-g11-von-neumann-machine)). The toy machine has $256$ cells of one byte, four registers, a program counter, a [stack pointer](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-subroutine) and three flags, and the grade 11 project built its [assembler](https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language#def-g11-von-neumann-machine-assembly) and simulator (chapter [21](https://one-course.com/books/computer-science/2/en/chapter/21-project-an-assembler-and-simulator-for-the-toy-machine#ch-g11-project-toy-machine)). A [recursive function](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#def-g12-recursion-recursion) calls itself on a smaller case (chapter [22](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#ch-g12-recursion)).

## 34.1 A program is data

The text of a Python program is a string. Python’s own module `ast` turns that string into a tree of the program’s parts, which another program can walk and count.

```python
"""A program reading a program: Python's ast module parses euclid.py."""
import ast
from pathlib import Path

source = Path("euclid.py").read_text()
tree = ast.parse(source)                         # the text becomes a tree
kinds = {}
for node in ast.walk(tree):
    name = type(node).__name__
    kinds[name] = kinds.get(name, 0) + 1
print(len(source), "characters,", len(source.splitlines()), "lines")
print("functions:", [n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)])
print("while loops:", kinds.get("While", 0), "  for loops:", kinds.get("For", 0),
      "  calls:", kinds.get("Call", 0))
```

***Listing 34.1.** A program that reads another program’s text. code/grade-12/13-halting-problem/listings/read_program.py*

```
$ python read_program.py
219 characters, 10 lines
functions: ['gcd']
while loops: 1   for loops: 0   calls: 2
```

***Output 34.1.** The program `euclid.py` of the last section, seen as data.*

A toy-machine program is even more plainly data: after assembly, it is $256$ numbers. The simulator reads them as instructions only when it runs them, and a single changed byte changes what the program does.

```python
"""A toy-machine program kept in a Python string: data until the simulator runs it."""
from toymachine import Machine, assemble

COUNTDOWN = """
        LOADI R0, 3
        LOADI R1, 1
loop:   OUT   R0
        SUB   R0, R1
        JNZ   loop
        HALT
"""
code = assemble(COUNTDOWN)                       # 256 bytes of memory
print("the first ten bytes:", code[:10])
m = Machine(code)
m.run()
print("outputs:", m.outputs, " steps:", m.steps)
code[1] = 5                                      # change one byte of the program
m = Machine(code)
m.run()
print("after changing byte 1 to 5:", m.outputs, " steps:", m.steps)
```

***Listing 34.2.** A program in a string, assembled, run, changed, run again. code/grade-12/13-halting-problem/listings/toy_interpreter_use.py*

```
$ python toy_interpreter_use.py
the first ten bytes: [4, 3, 5, 1, 80, 0, 20, 1, 64, 4]
outputs: [3, 2, 1]  steps: 12
after changing byte 1 to 5: [5, 4, 3, 2, 1]  steps: 18
```

***Output 34.2.** Byte $1$ is the operand of the first `LOADI`: the starting count.*

**Definition 34.1 (Compiler).**

A *compiler* is a program that reads a program written in one language and writes an equivalent program in another, usually the machine code of a processor, without running it. An *interpreter* reads a program and carries out its instructions itself, as the toy machine’s simulator does.

![A program whose input is another program. Counting its loops, running it and translating it are all computations on its text.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-halting-problem/fig-fc1fdc8aae79.svg)

*A program whose input is another program. Counting its loops, running it and translating it are all computations on its text.*

Programs that read programs are everywhere: the Python interpreter, [compilers](#def-g12-halting-problem-compiler), the checker `ruff` that this book runs on every listing, and the browser that runs the scripts of a web page. Whether one of them could also tell, for every program, whether it stops, is the question of this chapter.

## 34.2 Decidable problems

**Definition 34.2 (Decision problem, decidable problem).**

A *decision problem* is a question with a yes-or-no answer about an input: “is this number prime?”, “does this [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) have a cycle?”. It is *decidable* when some algorithm answers it correctly for every input, always stopping after a finite number of steps.

Primality is [decidable](#def-g12-halting-problem-decidable): trying every divisor up to the square root always ends. So is a bounded version of the question of this chapter: “does this toy program halt within $k$ steps?”. Run it for at most $k$ steps, and look.

```python
"""Halting within k steps is decidable: run at most k steps and look."""
from programs import COUNTDOWN, FOREVER, WRAP
from toymachine import Machine, assemble


def halts_within(text, k):
    m = Machine(assemble(text))
    while not m.halted and m.steps < k:
        m.step()
    return m.halted, m.steps


for name, text in [("COUNTDOWN", COUNTDOWN), ("FOREVER", FOREVER), ("WRAP", WRAP)]:
    for k in (100, 1000):
        halted, steps = halts_within(text, k)
        verdict = f"halts after {steps} steps" if halted else "has not halted"
        print(f"{name:9} within {k:4} steps: {verdict}")
```

***Listing 34.3.** Halting within $k$ steps, decided by running. code/grade-12/13-halting-problem/listings/halts_within.py*

```python
"""Three toy programs without input, used by the listings of the chapter."""

COUNTDOWN = """
        LOADI R0, 3
        LOADI R1, 1
loop:   OUT   R0
        SUB   R0, R1
        JNZ   loop
        HALT
"""
FOREVER = """
loop:   JMP   loop
"""
WRAP = """
loop:   ADDI  R0, 1      ; 1, 2, ..., 255, then 0 again
        JNZ   loop
        HALT
"""
SPIN = """
loop:   ADDI  R0, 1      ; counts for ever, round and round
        JMP   loop
"""
```

***Listing 34.4.** The toy programs of the chapter. code/grade-12/13-halting-problem/listings/programs.py*

```
$ python halts_within.py
COUNTDOWN within  100 steps: halts after 12 steps
COUNTDOWN within 1000 steps: halts after 12 steps
FOREVER   within  100 steps: has not halted
FOREVER   within 1000 steps: has not halted
WRAP      within  100 steps: has not halted
WRAP      within 1000 steps: halts after 513 steps
```

***Output 34.3.** “Has not halted” is a correct answer to the bounded question, and no answer to the real one: `WRAP` needed $513$ steps.*

Running and watching gives a yes when the program stops. When it has not stopped yet, it gives nothing: the program may stop at the next step, or never. The real question has no $k$.

**Definition 34.3 (Computable function).**

A function from inputs to outputs is *computable* when some program computes it: for every input, the program stops and gives the function’s value. A [decision problem](#def-g12-halting-problem-decidable) is [decidable](#def-g12-halting-problem-decidable) exactly when its yes-or-no function is computable.

## 34.3 The halting problem

The *halting problem* asks, for a program $P$ and an input $x$: does $P$, run on $x$, ever stop?

**Theorem 34.4 (Undecidability of the halting problem).**

No program decides the halting problem: for every program `halts(program, data)` that always stops and answers yes or no, there is a program and an input on which its answer is wrong.

**Proof.** Take any function `halts` that always stops with `True` or `False`. Build from it the program below, `contrarian`: on an input `program`, it asks `halts` whether `program` stops when given itself as its input, and then does the opposite.

```python
"""The program of the proof. Given any function that claims to decide halting,
it builds a program on which that function is wrong."""


def make_contrarian(halts):
    """halts(program, data) claims to say whether program(data) ever stops."""

    def contrarian(program):
        if halts(program, program):              # "program stops on itself"
            while True:                          # then run for ever
                pass
        return "stopped"                         # else stop at once

    return contrarian
```

***Listing 34.5.** The program of the proof. code/grade-12/13-halting-problem/listings/contrarian.py*

Now run `contrarian` on itself, and call $c$ that run. Since `halts` always stops, `contrarian` reaches its `if`, and there are two cases.

- If `halts(contrarian, contrarian)` is `True` , the claim is “ $c$ stops”. But then $c$ enters `while True` and never stops: the claim was wrong.
- If it is `False` , the claim is “ $c$ never stops”. But then $c$ returns at once: wrong again.

Either way `halts` is wrong on the program `contrarian` with the input `contrarian`. Since `halts` was any function, none decides halting. ∎

![The two cases of the proof. Whatever halts answers about c, the program c reads that answer and does the other thing.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-halting-problem/fig-31e92aa90c9e.svg)

*The two cases of the proof. Whatever `halts` answers about $c$, the program $c$ reads that answer and does the other thing.*

The argument can be tried on real candidates. Each of the three below is a function that always answers; each one is built into its own contrarian, and the contrarian is run under a watch that gives up after $100\,000$ lines of Python.

```python
"""Three would-be deciders, each one defeated by its own contrarian program."""
import inspect
import sys

from contrarian import make_contrarian


class OutOfTime(Exception):
    pass


def run_for(f, x, budget):
    """Run f(x), but give up after budget lines of Python have been executed."""
    count = 0

    def tracer(frame, event, arg):
        nonlocal count
        if event == "line":
            count += 1
            if count > budget:
                raise OutOfTime
        return tracer

    sys.settrace(tracer)
    try:
        return f"stops, returning {f(x)!r}"
    except OutOfTime:
        return f"still running after {budget} lines"
    finally:
        sys.settrace(None)
```

***Listing 34.6.** Running a function under a watch that stops it after a budget of lines. code/grade-12/13-halting-problem/listings/try_contrarian.py*

```python
def always_yes(program, data):
    return True


def always_no(program, data):
    return False


def no_endless_loop(program, data):
    """Looks at the source: a program without 'while True' is said to stop."""
    return "while True" not in inspect.getsource(program)


for decider in [always_yes, always_no, no_endless_loop]:
    c = make_contrarian(decider)
    claim = "stops" if decider(c, c) else "runs for ever"
    print(f"{decider.__name__:15} says c(c) {claim:13}; in fact c(c)",
          run_for(c, c, 100_000))
```

***Listing 34.7.** Three would-be deciders, each against its own contrarian. code/grade-12/13-halting-problem/listings/try_contrarian.py*

```
$ python try_contrarian.py
always_yes      says c(c) stops        ; in fact c(c) still running after 100000 lines
always_no       says c(c) runs for ever; in fact c(c) stops, returning 'stopped'
no_endless_loop says c(c) runs for ever; in fact c(c) stops, returning 'stopped'
```

***Output 34.4.** Each candidate is wrong about its own contrarian, as the proof says it must be.*

The proof is a *diagonal* argument. Imagine a table with one row per program and one column per input, a tick where the program stops on that input. The contrarian’s row differs from every row of the table: on the input of row $i$, it does the opposite of what program $i$ does on that same input, on the diagonal. So its row is in no place of the table, although the table was supposed to list every program.

![The diagonal. The contrarian does the opposite of each circled entry, so its row differs from row i in column i: it is none of the programs listed.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-halting-problem/fig-8eefbc9e80a8.svg)

*The diagonal. The contrarian does the opposite of each circled entry, so its row differs from row $i$ in column $i$: it is none of the programs listed.*

**History — Church and Turing, 1936.**

In April 1936 Alonzo Church published, in the *American Journal of Mathematics*, “An unsolvable problem of elementary number theory”. Alan Turing’s “On [computable](#def-g12-halting-problem-computable) numbers, with an application to the Entscheidungsproblem”, in the *Proceedings of the London Mathematical Society* (volume dated 1937), described an imaginary machine that reads and writes symbols on a tape, and showed that some questions about such machines cannot be answered by any machine. The two works reached the same limit by different routes.

## 34.4 What else cannot be decided, and what is too slow

The same argument, or a reduction to halting, shows that many questions about what programs do are undecidable: does this program ever print a given line? Do these two programs give the same output for every input? Is this line of the program ever reached? A general statement covers them all: any question about the *behaviour* of programs, what they compute rather than how their text looks, that is true for some programs and false for others, is undecidable. This book states it without proof. Checkers like `ruff` are useful because they answer questions about the text, or answer “maybe” when unsure.

[Decidable](#def-g12-halting-problem-decidable) does not mean feasible. The bounded question of section [34.2](#sec-34-2) is decided by running $k$ steps, and $k$ can be huge. A search through every subset of $n$ objects always ends, after $2^n$ tries: for $n = 100$, about $10^{30}$, far beyond any machine. The problem of this chapter meets a [decidable](#def-g12-halting-problem-decidable) question whose algorithm would need more steps than that by hundreds of orders of magnitude.

## 34.5 One algorithm, several languages

What a program can compute does not depend on the language it is written in. Euclid’s algorithm, for instance, runs in Python, in toy assembly with only subtraction, and in [SQL](https://one-course.com/books/computer-science/2/en/chapter/30-relational-databases-and-sql#def-g12-relational-databases-sql-sql) with a recursive query.

```python
"""Euclid's algorithm: the greatest common divisor of a and b."""


def gcd(a, b):
    while b > 0:
        a, b = b, a % b                          # the remainder replaces the pair
    return a


print(gcd(252, 198))
```

***Listing 34.8.** Euclid in Python. code/grade-12/13-halting-problem/listings/euclid.py*

```
$ python euclid.py
18
```

***Output 34.5.** The greatest common divisor of $252$ and $198$.*

```text
; euclid_asm.toy -- the gcd of 252 and 198 by subtraction (no division here)
        LOADI R0, 252
        LOADI R1, 198
loop:   CMP   R0, R1
        JZ    done          ; equal: that is the gcd
        JC    swap          ; R0 < R1: exchange them first
        SUB   R0, R1        ; R0 = R0 - R1
        JMP   loop
swap:   PUSH  R0
        PUSH  R1
        POP   R0
        POP   R1
        JMP   loop
done:   OUT   R0
        HALT
```

***Listing 34.9.** Euclid on the toy machine, which has no division: subtract the smaller from the larger until they are equal. code/grade-12/13-halting-problem/listings/euclid_asm.toy*

```
$ python -m toymachine run euclid_asm.toy --trace
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  LOADI R0, 252      0   0   0   0  0 0 0
   2   2  LOADI R1, 198    252   0   0   0  0 0 0
   3   4  CMP R0, R1       252 198   0   0  0 0 0
  58   6  JZ 24             18  18   0   0  1 0 0
  59  24  OUT R0            18  18   0   0  1 0 0
18
  60  26  HALT              18  18   0   0  1 0 0
halted after 60 steps
```

***Output 34.6.** The same answer, $18$: the first and the last steps of the trace (each row shows the registers before its step), and $60$ steps in all. Some lines are left out.*

A recursive query starts from one row, then computes new rows from the last ones until no new row comes.

```
$ python sqlrun.py euclid_sql.sql
sql> WITH RECURSIVE pairs(a, b) AS (
...>     SELECT 252, 198
...>     UNION ALL
...>     SELECT b, a % b FROM pairs WHERE b > 0
...> )
...> SELECT a, b FROM pairs;
+-----+-----+
| a   | b   |
+-----+-----+
| 252 | 198 |
| 198 | 54  |
| 54  | 36  |
| 36  | 18  |
| 18  | 0   |
+-----+-----+
(5 rows)
```

***Output 34.7.** Euclid as a recursive query: each row is the next pair, and the last row holds the answer.*

| **Python** | **toy assembly** | **[SQL](https://one-course.com/books/computer-science/2/en/chapter/30-relational-databases-and-sql#def-g12-relational-databases-sql-sql)** |
| --- | --- | --- |
| `while b > 0:` | `loop: CMP R0, R1` | `WHERE b > 0` |
|  | `JZ done` | (stops when no row comes) |
| `a, b = b, a % b` | `SUB R0, R1` (or swap) | `SELECT b, a % b FROM pairs` |
| `return a` | `done: OUT R0` | the row where `b = 0` |
| $4$ turns of the loop | $6$ subtractions, $3$ swaps | $5$ rows |

*The same algorithm read in three languages. The step is the same idea everywhere: replace the pair by a smaller pair with the same common divisors.*

Every general-purpose language can compute what the others compute, given enough memory and time; the languages differ in convenience and speed. The halting problem is undecidable in all of them for the same reason.

## 34.6 Exercises

**Exercise 34.1 ★.**

What does `halts_within(WRAP, 512)` return? And `halts_within(WRAP, 513)`?

**Solution of Exercise 34.1.**

`(False, 512)`: after $512$ steps `WRAP` has not halted yet. `(True, 513)`: its `HALT` is the $513$th step.

**Exercise 34.2 ★.**

How many steps does `COUNTDOWN` make when its first line is `LOADI R0, 5`? Give a formula for `LOADI R0, n`.

**Solution of Exercise 34.2.**

Two `LOADI`, then $n$ turns of three instructions (`OUT`, `SUB`, `JNZ`), then `HALT`: $3n + 3$ steps, so $18$ for $n = 5$, as the chapter’s output shows, and $12$ for $n = 3$.

**Exercise 34.3 ★.**

What would `read_program.py` print for a file that contains only `for i in range(3): print(i)`?

**Solution of Exercise 34.3.**

With a final line break, `28 characters, 1 lines`; `functions: []`; `while loops: 0`, `for loops: 1`, `calls: 2`, the calls to `range` and `print`.

**Exercise 34.4 ★.**

Three programs and three inputs give the table “stops, loops, stops” / “stops, stops, stops” / “loops, loops, loops” (row $i$ is program $i$). Write the contrarian’s row and check that it differs from each row.

**Solution of Exercise 34.4.**

The diagonal reads stops, stops, loops; the contrarian does the opposite: loops, loops, stops. It differs from row $1$ in column $1$, from row $2$ in column $2$, from row $3$ in column $3$.

**Exercise 34.5 ★.**

Write `count_functions(path)`, which counts the functions defined in a Python file, methods and nested functions included.

**Solution of Exercise 34.5.**

    `def count_functions(path):`

        `tree = ast.parse(Path(path).read_text())`

        `return sum(isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))`

                `for n in ast.walk(tree))`

`ast.walk` visits every node, inside classes and functions too. The tests count $3$ in a file with a function, a nested function and a method.

**Exercise 34.6 ★★.**

Explain why “does program $P$ halt on input $x$ within $k$ steps?” is [decidable](#def-g12-halting-problem-decidable), although the halting problem is not.

**Solution of Exercise 34.6.**

The algorithm “run $P$ on $x$ for at most $k$ steps, then answer” always stops, after at most $k$ steps, and its answer is right: either $P$ halted during those steps or it did not. The halting problem has no bound: no $k$ is large enough for every program.

**Exercise 34.7 ★★.**

A would-be decider runs `program(data)` and answers `True` when it returns. What does it answer on a program that never stops? Why does it escape the theorem only in appearance?

**Solution of Exercise 34.7.**

It never answers: it waits for ever with the program. So it does not always stop, and it is not a decider in the sense of the theorem, which is about functions that always answer. It decides the “yes” cases only.

**Exercise 34.8 ★★.**

Write `first_repeat(text)`, which runs a toy program without `IN` and returns the step at which a state comes back and the length of the cycle, or `None` if the program halts. Apply it to `SPIN` and `FOREVER`.

**Solution of Exercise 34.8.**

    `def first_repeat(text):`

        `m, seen = Machine(assemble(text)), {}`

        `while not m.halted:`

            `s = state(m)`

            `if s in seen:`

                `return m.steps, m.steps - seen[s]`

            `seen[s] = m.steps`

            `m.step()`

        `return None`

The dictionary keeps the step at which each state was first met. `SPIN`: $(513, 512)$, a cycle of $512$ steps. `FOREVER`: $(1, 1)$.

**Exercise 34.9 ★★.**

A tiny machine has $16$ cells of one byte, two registers of one byte, a program counter of $4$ bits and one flag. How many states can it be in?

**Solution of Exercise 34.9.**

$16 \times 8 + 2 \times 8 + 4 + 1 = 149$ bits, so $2^{149}$ states, about $7 \times 10^{44}$.

**Exercise 34.10 ★★.**

The candidate `short_is_stopping` says that a program stops when its source has fewer than $200$ characters. The source of `contrarian` has $265$. What does `try_contrarian.py` print for it?

**Solution of Exercise 34.10.**

$265 \ge 200$, so the candidate says the contrarian runs for ever; the contrarian then returns at once. The line printed is

    `short_is_stopping says c(c) runs for ever; in fact c(c)`

        `stops, returning 'stopped'`

and the tests check it.

**Exercise 34.11 ★★.**

Argue that “does this program ever print anything?” is undecidable: from a decider for it, build a decider for halting.

**Solution of Exercise 34.11.**

Suppose `prints(program, data)` decides whether a program ever prints. Given $P$ and $x$, build the program $Q$: “run $P$ on $x$ with all its printing thrown away, then print `done`”. $Q$ prints something exactly when $P$ halts on $x$. So `prints(Q, ...)` would decide whether $P$ halts on $x$, for every $P$ and $x$, which the theorem forbids. Hence no such `prints` exists.

**Exercise 34.12 ★★★.**

Write the proof of the theorem in your own words, and say exactly where it uses that `halts` always stops.

**Solution of Exercise 34.12.**

Suppose some program always answers, correctly, whether a program stops on an input. Build the contrarian, which asks it about a program run on itself and does the opposite. Ask about the contrarian run on itself: a “yes” makes it loop, a “no” makes it stop, so the answer is wrong in both cases, against the supposition. The proof uses that `halts` always stops in the line “the contrarian reaches its `if`”: if `halts` could run for ever, the contrarian could run for ever inside it, and a “no” would never have been given, so nothing would be wrong.

**Exercise 34.13 ★★★.**

Prove that a machine with $S$ possible states, whose next state depends only on its current one, either halts within $S$ steps or never halts.

**Solution of Exercise 34.13.**

Suppose the machine runs $S$ steps without halting. It has then been in $S + 1$ states, counting the first, among only $S$ possible ones: two of them are equal (the pigeonhole principle), say at steps $i < j$. Since the next state depends only on the current one, the states from step $j$ on repeat those from step $i$ on: the run goes round the cycle from $i$ to $j$ for ever, and none of those states is a halted one, since the machine went on after each. So it never halts. Hence a machine that halts does so within $S$ steps.

**Exercise 34.14 ★★★.**

Write a toy program that reads $a$ and $b$ with `IN` and prints $a \times b$ by repeated addition. Test it from Python on several pairs, including $b = 0$.

**Solution of Exercise 34.14.**

    `IN R0` `IN R1` `LOADI R2, 0` `LOADI R3, 1`

    `CMP R1, R2` `JZ done` (if $b = 0$, the product stays $0$)

    `loop: ADD R2, R0` `SUB R1, R3` `JNZ loop`

    `done: OUT R2` `HALT`

Without the test, $b = 0$ would first become $255$ after the subtraction, and the loop would run $256$ times. The tests compare with $a \times b$ modulo $256$ for $a$ in $0$, $7$, $14$, $21$, $28$ and $b$ from $0$ to $8$: the machine computes modulo $256$.

**Exercise 34.15 ★★★.**

Why is a running Python program not a machine with finitely many states, so that the repeat detector of the problem cannot decide its halting?

**Solution of Exercise 34.15.**

Python’s integers have no fixed size, and lists, strings and dictionaries can grow as long as the program likes. A program that keeps adding $1$ to an integer, or appending to a list, never returns to an earlier state: there is no finite set of states for the pigeonhole principle to work on. (A real computer’s memory is finite, but so large that the bound would be of no use, and a program that reaches its limit stops with an error rather than looping.)

## 34.7 Problem: A Machine That Can Be Decided

**Problem 34.1.**

Weekend problem — deciding the toy machine

The theorem is about programs that may use as much memory as they like. The toy machine has $256$ bytes. This problem shows that for its programs without `IN`, halting is [decidable](#def-g12-halting-problem-decidable), and measures the price.

```python
"""For the toy machine without IN, halting is decidable: watch for a repeated state."""
from programs import COUNTDOWN, FOREVER, SPIN, WRAP
from toymachine import Machine, assemble


def state(m):
    """Everything that decides the future: memory, registers, PC, SP, flags."""
    return bytes(m.mem + m.reg + [m.pc, m.sp, m.flags["Z"], m.flags["N"], m.flags["C"]])


def decide(text):
    m, seen = Machine(assemble(text)), set()
    while not m.halted:
        s = state(m)
        if s in seen:                            # the same state: the same future
            return "never halts", m.steps, len(seen)
        seen.add(s)
        m.step()
    return "halts", m.steps, len(seen)


for name, text in [("COUNTDOWN", COUNTDOWN), ("FOREVER", FOREVER), ("WRAP", WRAP),
                   ("SPIN", SPIN)]:
    verdict, steps, states = decide(text)
    print(f"{name:9}: {verdict:11} decided after {steps:3} steps,"
          f" {states:3} states stored")
```

***Listing 34.10.** Deciding halting by watching for a repeated state. code/grade-12/13-halting-problem/listings/repeat_detector.py*

```
$ python repeat_detector.py
COUNTDOWN: halts       decided after  12 steps,  12 states stored
FOREVER  : never halts decided after   1 steps,   1 states stored
WRAP     : halts       decided after 513 steps, 513 states stored
SPIN     : never halts decided after 513 steps, 513 states stored
```

***Output 34.8.** Four programs, four verdicts.*

**Part I — The state of the machine.**

1. List what `state` records. Why do the outputs printed so far not belong to it?
2. Why must a program without `IN` behave the same way each time it is in the same state?
3. How many bytes and bits make up a state? Count memory, registers, `PC` , `SP` and flags.
4. How many different states can the machine be in?

**Part II — The bound.**

5. Show that a run of more steps than there are states meets some state twice.
6. Show that a run that meets a state twice never halts.
7. Conclude: every toy program without input halts or repeats a state within how many steps?
8. Write that number as a power of ten.

**Part III — The detector.**

9. Why does `decide` always stop?
10. Why does it decide `FOREVER` after one step?
11. Explain the $513$ steps of `SPIN` : what repeats, and when?
12. `WRAP` and `SPIN` both take $513$ steps. Why do they get different verdicts?
13. Each stored state takes about $260$ bytes. How much memory would the detector need for a program that runs $10^9$ steps before repeating?
14. The detector stores every state. Describe a way to detect a repeat while keeping only two machines (one stepping once, the other twice).

**Part IV — Why it fails for Python.**

15. What does `IN` change in Part I?
16. Why does the proof of the theorem not apply to the toy machine without input?
17. Could `contrarian` be written as a toy program without input that takes another toy program as data? What stops it?
18. Why is the bound of question 7 useless in practice?
19. Why does nothing like this bound exist for Python programs?
20. State the result: what is [decidable](#def-g12-halting-problem-decidable) for the toy machine without input, within what bound, and why it does not contradict the theorem.

**Solution of Problem 34.1.**

**1.** The $256$ cells of memory, the four registers, `PC`, `SP` and the three flags. The outputs already printed have no effect on the next step: no instruction reads them.

**2.** Each step computes the next state from the current one alone; without `IN`, nothing from outside enters. The same state is always followed by the same next state.

**3.** $256 + 4 + 1 + 1 = 262$ bytes, that is $2096$ bits, plus $3$ flag bits: $2099$ bits.

**4.** $2^{2099}$: each of the $2099$ bits can be $0$ or $1$.

**5.** After $n$ steps the run has passed through $n + 1$ states. If $n + 1$ exceeds the number of states, two are equal: the pigeonhole principle.

**6.** From the second time on, the run repeats what followed the first time, step for step, and comes back to the same state again, for ever. No `HALT` lies on that cycle, since the run went on after each of its states.

**7.** Within $2^{2099}$ steps (exercise [34.13](#exo-g12-halting-problem-13)).

**8.** $2099 \times \log_{10} 2 \approx 631.9$: about $7 \times 10^{631}$.

**9.** Each step either halts, or meets a state already seen, or adds a new state to `seen`. The last can happen at most $2^{2099}$ times, so the loop ends.

**10.** `FOREVER` is `JMP` to address $0$: after one step, `PC` is $0$ again and nothing else has changed. The state after step $1$ is the starting state.

**11.** `SPIN` adds $1$ to `R0` and jumps back, so `R0` goes round its $256$ values in $512$ steps. The very first state, with every flag at $0$, never comes back: when `R0` wraps from $255$ to $0$, `ADDI` sets `Z` and `C`. The state after step $1$ (`R0` $= 1$, flags $0$, `PC` $= 2$) is the first to recur, after step $513$: a cycle of $512$ steps.

**12.** `WRAP` jumps back with `JNZ`, so when `R0` wraps to $0$ it falls through to `HALT`, at step $513$. `SPIN` jumps back with `JMP`, whatever the flags.

**13.** $10^9 \times 260$ bytes, about $260$ gigabytes, for a program that is short to write.

**14.** Run two machines from the same start, one stepping once and the other twice per round, and compare their states after each round. If the program loops, the fast one enters the cycle and gains one step per round on the slow one, so they meet; if it halts, the fast one sees `HALT`. Only two states are kept.

**15.** With `IN`, the next state also depends on the next number read, which is not in the state. The same state can be followed by different states, and the input may be as long as one likes: the counting of Part I no longer bounds anything.

**16.** The theorem is about a decider that is itself a program of the model and works on every program of it, including the contrarian built from it. The repeat detector is a Python program, with far more memory than $256$ bytes; it is not a toy program, so it cannot be fed to itself as one.

**17.** A contrarian must receive a program as data and run the decider on it. Without `IN`, a toy program receives nothing; and the decider, with its set of up to $2^{2099}$ states, would never fit in $256$ bytes.

**18.** At $10^9$ steps per second, $7 \times 10^{631}$ steps take about $2 \times 10^{615}$ years. The detector is correct, and it would never finish on a program that uses its states well.

**19.** A Python program can use ever more memory, with integers and lists that grow without limit, so it has no finite number of states: no bound like $2^{2099}$ exists.

**20.** **For toy-machine programs without `IN`, halting is [decidable](#def-g12-halting-problem-decidable): every such program halts or repeats a state within $2^{2099}$, about $7 \times 10^{631}$, steps, since a state has $262$ bytes and $3$ flag bits. The repeat detector decides it, but it is no toy program, so the theorem is not contradicted; and the bound is far beyond any machine.**
