计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本:English。

High School Computer Science · 10–12 年级

34What 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 names the instructions of the processor (chapter 13). The toy machine has 256256 cells of one byte, four registers, a program counter, a stack pointer and three flags, and the grade 11 project built its assembler and simulator (chapter 21). A recursive function calls itself on a smaller case (chapter 22).

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.

"""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 256256 numbers. The simulator reads them as instructions only when it runs them, and a single changed byte changes what the program does.

"""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 11 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.
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, 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 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: 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 kk steps?”. Run it for at most kk steps, and look.

"""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 kk steps, decided by running. code/grade-12/13-halting-problem/listings/halts_within.py
"""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 513513 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 kk.

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 is decidable exactly when its yes-or-no function is computable.

34.3 The halting problem

The halting problem asks, for a program PP and an input xx: does PP, run on xx, 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.

"""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 cc that run. Since halts always stops, contrarian reaches its if, and there are two cases.

  • If halts(contrarian, contrarian) is True, the claim is “cc stops”. But then cc enters while True and never stops: the claim was wrong.
  • If it is False, the claim is “cc never stops”. But then cc 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.
The two cases of the proof. Whatever halts answers about cc, the program cc 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 000100\,000 lines of 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
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 ii, it does the opposite of what program ii 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.
The diagonal. The contrarian does the opposite of each circled entry, so its row differs from row ii in column ii: 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 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 does not mean feasible. The bounded question of section 34.2 is decided by running kk steps, and kk can be huge. A search through every subset of nn objects always ends, after 2n2^n tries: for n=100n = 100, about 103010^{30}, far beyond any machine. The problem of this chapter meets a 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 with a recursive query.

"""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 252252 and 198198.
; 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, 1818: the first and the last steps of the trace (each row shows the registers before its step), and 6060 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.
Pythontoy assemblySQL
while b > 0:loop: CMP R0, R1WHERE b > 0
JZ done(stops when no row comes)
a, b = b, a % bSUB R0, R1 (or swap)SELECT b, a % b FROM pairs
return adone: OUT R0the row where b = 0
44 turns of the loop66 subtractions, 33 swaps55 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

Solution of Exercise 34.1.

(False, 512): after 512512 steps WRAP has not halted yet. (True, 513): its HALT is the 513513th 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

Solution of Exercise 34.2.

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

Exercise 34.3 ★

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

Solution

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 ii is program ii). Write the contrarian’s row and check that it differs from each row.

Solution

Solution of Exercise 34.4.

The diagonal reads stops, stops, loops; the contrarian does the opposite: loops, loops, stops. It differs from row 11 in column 11, from row 22 in column 22, from row 33 in column 33.

Exercise 34.5 ★

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

Solution

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 33 in a file with a function, a nested function and a method.

Exercise 34.6 ★★

Explain why “does program PP halt on input xx within kk steps?” is decidable, although the halting problem is not.

Solution

Solution of Exercise 34.6.

The algorithm “run PP on xx for at most kk steps, then answer” always stops, after at most kk steps, and its answer is right: either PP halted during those steps or it did not. The halting problem has no bound: no kk 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

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

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)(513, 512), a cycle of 512512 steps. FOREVER: (1,1)(1, 1).

Exercise 34.9 ★★

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

Solution

Solution of Exercise 34.9.

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

Exercise 34.10 ★★

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

Solution

Solution of Exercise 34.10.

265≥200265 \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

Solution of Exercise 34.11.

Suppose prints(program, data) decides whether a program ever prints. Given PP and xx, build the program QQ: “run PP on xx with all its printing thrown away, then print done”. QQ prints something exactly when PP halts on xx. So prints(Q, ...) would decide whether PP halts on xx, for every PP and xx, 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

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 SS possible states, whose next state depends only on its current one, either halts within SS steps or never halts.

Solution

Solution of Exercise 34.13.

Suppose the machine runs SS steps without halting. It has then been in S+1S + 1 states, counting the first, among only SS possible ones: two of them are equal (the pigeonhole principle), say at steps i<ji < j. Since the next state depends only on the current one, the states from step jj on repeat those from step ii on: the run goes round the cycle from ii to jj 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 SS steps.

Exercise 34.14 ★★★

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

Solution

Solution of Exercise 34.14.

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

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

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

done: OUT R2 HALT

Without the test, b=0b = 0 would first become 255255 after the subtraction, and the loop would run 256256 times. The tests compare with a×ba \times b modulo 256256 for aa in 00, 77, 1414, 2121, 2828 and bb from 00 to 88: the machine computes modulo 256256.

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

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 11 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 256256 bytes. This problem shows that for its programs without IN, halting is decidable, and measures the price.

"""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.

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

Part III — The detector.

  1. Why does decide always stop?
  2. Why does it decide FOREVER after one step?
  3. Explain the 513513 steps of SPIN: what repeats, and when?
  4. WRAP and SPIN both take 513513 steps. Why do they get different verdicts?
  5. Each stored state takes about 260260 bytes. How much memory would the detector need for a program that runs 10910^9 steps before repeating?
  6. 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.

  1. What does IN change in Part I?
  2. Why does the proof of the theorem not apply to the toy machine without input?
  3. Could contrarian be written as a toy program without input that takes another toy program as data? What stops it?
  4. Why is the bound of question 7 useless in practice?
  5. Why does nothing like this bound exist for Python programs?
  6. State the result: what is decidable for the toy machine without input, within what bound, and why it does not contradict the theorem.
Solution

Solution of Problem 34.1.

1. The 256256 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=262256 + 4 + 1 + 1 = 262 bytes, that is 20962096 bits, plus 33 flag bits: 20992099 bits.

4. 220992^{2099}: each of the 20992099 bits can be 00 or 11.

5. After nn steps the run has passed through n+1n + 1 states. If n+1n + 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 220992^{2099} steps (exercise 34.13).

8. 2099×log⁡102≈631.92099 \times \log_{10} 2 \approx 631.9: about 7×106317 \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 220992^{2099} times, so the loop ends.

10. FOREVER is JMP to address 00: after one step, PC is 00 again and nothing else has changed. The state after step 11 is the starting state.

11. SPIN adds 11 to R0 and jumps back, so R0 goes round its 256256 values in 512512 steps. The very first state, with every flag at 00, never comes back: when R0 wraps from 255255 to 00, ADDI sets Z and C. The state after step 11 (R0 =1= 1, flags 00, PC =2= 2) is the first to recur, after step 513513: a cycle of 512512 steps.

12. WRAP jumps back with JNZ, so when R0 wraps to 00 it falls through to HALT, at step 513513. SPIN jumps back with JMP, whatever the flags.

13. 109×26010^9 \times 260 bytes, about 260260 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 256256 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 220992^{2099} states, would never fit in 256256 bytes.

18. At 10910^9 steps per second, 7×106317 \times 10^{631} steps take about 2×106152 \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 220992^{2099} exists.

20. For toy-machine programs without IN, halting is decidable: every such program halts or repeats a state within 220992^{2099}, about 7×106317 \times 10^{631}, steps, since a state has 262262 bytes and 33 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.

本章定义的术语

在术语表中查看全部 1050 个术语