Computer Science · Book 2 · Grades 10–12

High School Computer Science

High School Computer Science · Grades 10–12

22Recursion

A folder holds files and other folders, which hold files and other folders, as deep as anyone likes. How many files does it hold in all? A loop does not know how deep to go. But the question has a short answer in terms of itself: the files of a folder are its own files, plus the files of each folder inside it. A function that follows that sentence calls itself, and counts every file of the tree.

Such functions are called recursive. This chapter writes them, watches the machine run them, proves them correct, turns some of them back into loops, and ends on a famous puzzle whose recursive solution takes three lines and whose cost runs to hundreds of billions of years.

You already know

A function has parameters, local names and a returned value (the first book of the series). A loop is proved correct with an invariant and stops by a variant (chapter 16). A proof by induction shows a property for 00, then for n+1n + 1 whenever it holds for nn (the mathematics book, grade 12). Folders and paths (chapter 14).

22.1 A function that calls itself

Definition 22.1 (Recursive function, recursion)

A recursive function is a function whose body calls the function itself. Recursion is the method of solving a problem by reducing it to smaller instances of the same problem.

Definition 22.2 (Base case, recursive case)

The base case of a recursive function is an input for which it answers without calling itself. The recursive case is the part of the body that calls the function on smaller inputs and builds the answer from theirs.

The factorial n!=1×2×⋯×nn! = 1 \times 2 \times \dots \times n, with 0!=10! = 1, satisfies n!=n×(n−1)!n! = n \times (n - 1)!: the definition is already recursive. So are the sum of a list, its first element plus the sum of the rest, and the power xn=x×xn−1x^n = x \times x^{n-1}.

def factorial(n):
    """n! = 1 x 2 x ... x n, for a whole number n >= 0."""
    if n == 0:                       # base case
        return 1
    return n * factorial(n - 1)      # recursive case


def sum_list(t):
    """The sum of the numbers of the list t."""
    if t == []:
        return 0
    return t[0] + sum_list(t[1:])


def power(x, n):
    """x to the power n, for a whole number n >= 0."""
    if n == 0:
        return 1
    return x * power(x, n - 1)


if __name__ == "__main__":
    print([factorial(n) for n in range(8)])
    print(factorial(25))
    print(sum_list([3, 1, 4, 1, 5]), power(2, 10))
Listing 22.1. Three recursive functions, each with a base case and a recursive case. code/grade-12/01-recursion/listings/factorial.py
$ python factorial.py
[1, 1, 2, 6, 24, 120, 720, 5040]
15511210043330985984000000
14 1024
Output 22.1. Python’s integers have no size limit: 25!25! has 2626 digits.

To see what happens, the next version prints each call and each return, indented by its depth.

def factorial(n, depth=0):
    print("    " * depth + f"factorial({n}) called")
    if n == 0:
        result = 1
    else:
        result = n * factorial(n - 1, depth + 1)
    print("    " * depth + f"factorial({n}) returns {result}")
    return result


factorial(4)
Listing 22.2. The factorial, telling its calls and returns. code/grade-12/01-recursion/listings/trace_calls.py
$ python trace_calls.py
factorial(4) called
    factorial(3) called
        factorial(2) called
            factorial(1) called
                factorial(0) called
                factorial(0) returns 1
            factorial(1) returns 1
        factorial(2) returns 2
    factorial(3) returns 6
factorial(4) returns 24
Output 22.2. Five calls go down to the base case; then five returns come back up, each finishing a multiplication.

22.2 The call stack

Definition 22.3 (Call stack, frame)

Each call of a function gets a frame: a region of memory holding its arguments, its local names and the place to return to. The frames of the calls not yet finished form the call stack: a call pushes a frame on top, and a return pops it.

Every call of factorial has its own n: the five n of the trace exist at the same time, one per frame, and do not overwrite one another. This is the stack of the toy machine’s CALL and RET (chapter 13), kept by Python for every call.

The call stack of factorial(4) at its deepest point: six frames, the base case on top. Each frame keeps its own n until the call above it returns.
The call stack of factorial(4) at its deepest point: six frames, the base case on top. Each frame keeps its own n until the call above it returns.

The stack has a limit. A function that never reaches a base case, or reaches it too deep, fills the stack; Python stops it with RecursionError before the memory is exhausted.

import sys


def countdown(n):
    if n == 0:
        return "done"
    return countdown(n - 1)


print("recursion limit:", sys.getrecursionlimit())
print(countdown(500))
sys.setrecursionlimit(100)           # lowered, to fail quickly
try:
    countdown(500)
except RecursionError as error:
    print("RecursionError:", error)
Listing 22.3. A recursion 500500 deep, then the same with the limit lowered to 100100. code/grade-12/01-recursion/listings/depth_error.py
$ python depth_error.py
recursion limit: 1000
done
RecursionError: maximum recursion depth exceeded
Output 22.3. The limit is 10001000 frames in this run; lowered below 500500, the same call fails.

The function sys.getrecursionlimit gives the maximum depth of Python’s stack, and the function sys.setrecursionlimit changes it; the documentation warns that too high a limit can crash the interpreter, since the limit is there to protect the machine’s own stack.

22.3 Proving a recursive function

A recursive function is proved correct by induction on the size of its input: the base case is checked directly, and the recursive case is correct if the calls it makes, on smaller inputs, are.

Method 22.4 (Proving a recursive function)

  1. Correctness. State the property P(n)P(n): “f(n) returns the right value”. Check PP on the base cases. Assume PP for the smaller inputs the recursive case calls, and deduce it for nn.
  2. Termination. Find a variant: a whole number, computed from the arguments, that is at least 00 and strictly smaller at each recursive call. The calls then cannot go on forever.

For factorial: P(n)P(n) is “factorial(n) returns n!n!”. P(0)P(0) holds, since it returns 1=0!1 = 0!. If P(n−1)P(n - 1) holds, then factorial(n) returns n×(n−1)!=n!n \times (n - 1)! = n!. By induction, P(n)P(n) holds for every n≥0n \ge 0. The variant is nn itself: a whole number, decreased by 11 at each call, which reaches the base case 00. For a negative nn there is no variant, and indeed factorial(-1) never stops calling itself.

22.4 Recursion and loops

When the recursive call is the last thing done with a simple result, the function can be rewritten as a loop that performs the same operations in order. The loop needs no stack, and reaches sizes the recursion cannot.

from factorial import factorial, sum_list


def factorial_loop(n):
    result = 1
    for k in range(1, n + 1):        # the multiplications the recursion does, in order
        result *= k
    return result


def sum_loop(t):
    total = 0
    for x in t:
        total += x
    return total


print(all(factorial(n) == factorial_loop(n) for n in range(100)))
print(sum_list(list(range(500))) == sum_loop(range(500)))
print(factorial_loop(3000) > 10**9000, "| factorial(3000) by recursion:", end=" ")
try:
    factorial(3000)
except RecursionError:
    print("RecursionError")
Listing 22.4. The factorial and the sum as loops, compared with their recursive forms. code/grade-12/01-recursion/listings/loop_version.py
$ python loop_version.py
True
True
True | factorial(3000) by recursion: RecursionError
Output 22.4. Same results; at 30003000 the recursion runs out of stack, the loop does not.

Recursion is the natural form when the data are themselves recursive: a folder of folders, a list of lists. The loop version would have to manage its own stack of what remains to visit.

"""Count the files under a folder, at any depth, on a tree built for the test."""
import tempfile
from pathlib import Path


def count_files(folder):
    total = 0
    for entry in folder.iterdir():
        if entry.is_dir():
            total += count_files(entry)      # a folder: count what it holds
        else:
            total += 1                       # a file: count it
    return total


TREE = ["school/notes.txt", "school/maths/ch1.txt", "school/maths/ch2.txt",
        "school/maths/old/ch0.txt", "photos/sea.jpg", "photos/2026/june/a.jpg",
        "photos/2026/june/b.jpg", "photos/2026/july/c.jpg", "todo.txt"]

with tempfile.TemporaryDirectory() as top:
    root = Path(top)
    for name in TREE:
        (root / name).parent.mkdir(parents=True, exist_ok=True)
        (root / name).write_text("")
    print("files:", count_files(root))
    print("in photos:", count_files(root / "photos"))
    print("in school/maths:", count_files(root / "school" / "maths"))
Listing 22.5. Counting files at any depth, on a tree the listing builds in a temporary folder. code/grade-12/01-recursion/listings/count_files.py
$ python count_files.py
files: 9
in photos: 4
in school/maths: 3
Output 22.5. Nine files in all; four under photos, two levels down for some.
def nested_sum(item):
    """The sum of all numbers in item: a number, or a list of items."""
    if not isinstance(item, list):
        return item
    return sum(nested_sum(x) for x in item)


marks = [12, [15, 9], [[8, 11], 14], [], [[[20]]]]
print(nested_sum(marks))
print(nested_sum(7), nested_sum([]))
Listing 22.6. The sum of a list of lists, of any depth. code/grade-12/01-recursion/listings/nested_sum.py
$ python nested_sum.py
89
7 0
Output 22.6. 12+15+9+8+11+14+20=8912 + 15 + 9 + 8 + 11 + 14 + 20 = 89; a number alone is its own sum, an empty list sums to 00.

22.5 Three classics

The towers of Hanoi

Three pegs, A, B and C; on A, nn disks of decreasing sizes. The disks must all go to C, moving one disk at a time, never putting a disk on a smaller one. The recursive solution follows from looking at the largest disk: to move it, the n−1n - 1 others must be out of the way, on B.

A wooden towers of Hanoi: every disk on the first peg, the largest at the bottom.
A wooden towers of Hanoi: every disk on the first peg, the largest at the bottom.
The decomposition, each panel showing the pegs after its step. The two moves of n - 1 disks are smaller instances of the same puzzle, with the pegs renamed; the largest disk never lies on a smaller one.
The decomposition, each panel showing the pegs after its step. The two moves of n−1n - 1 disks are smaller instances of the same puzzle, with the pegs renamed; the largest disk never lies on a smaller one.
def hanoi(n, start, goal, spare, moves):
    """Append to moves the moves taking n disks from start to goal."""
    if n == 0:
        return
    hanoi(n - 1, start, spare, goal, moves)      # the n - 1 smaller ones out of the way
    moves.append((n, start, goal))               # the largest disk
    hanoi(n - 1, spare, goal, start, moves)      # the n - 1 smaller ones back on top


if __name__ == "__main__":
    moves = []
    hanoi(3, "A", "C", "B", moves)
    for disk, a, b in moves:
        print(f"disk {disk}: {a} -> {b}")
    for n in [1, 2, 3, 4, 5, 10, 15, 20]:
        moves = []
        hanoi(n, "A", "C", "B", moves)
        print(f"n = {n:2}: {len(moves):7} moves, 2**n - 1 = {2**n - 1}")
Listing 22.7. The towers of Hanoi in three lines. code/grade-12/01-recursion/listings/hanoi.py
$ python hanoi.py
disk 1: A -> C
disk 2: A -> B
disk 1: C -> B
disk 3: A -> C
disk 1: B -> A
disk 2: B -> C
disk 1: A -> C
n =  1:       1 moves, 2**n - 1 = 1
n =  2:       3 moves, 2**n - 1 = 3
n =  3:       7 moves, 2**n - 1 = 7
n =  4:      15 moves, 2**n - 1 = 15
n =  5:      31 moves, 2**n - 1 = 31
n = 10:    1023 moves, 2**n - 1 = 1023
n = 15:   32767 moves, 2**n - 1 = 32767
n = 20: 1048575 moves, 2**n - 1 = 1048575
Output 22.7. The seven moves for three disks, and the counts up to 2020.

History — A puzzle sold with a legend

The puzzle was published in Paris in 18831883 by the mathematician Édouard Lucas, under the name “N. Claus de Siam”, an anagram of “Lucas d’Amiens”. It came with a legend: at the creation, 6464 gold disks had been placed on one needle, priests were moving them by the puzzle’s rules, and when they finished the universe would end.

Drawings that contain themselves

The Koch curve replaces a segment by four segments a third as long, the middle two forming a peak, and does the same to each of them, and so on. A recursive function computes the points; depth 00 is the segment itself.

"""Points of the Koch curve: each segment is replaced by four, recursively."""
import math


def koch(p, q, depth, points):
    """Append to points the curve from p to q, without q itself."""
    if depth == 0:
        points.append(p)
        return
    (x1, y1), (x2, y2) = p, q
    dx, dy = (x2 - x1) / 3, (y2 - y1) / 3
    a, b = (x1 + dx, y1 + dy), (x1 + 2 * dx, y1 + 2 * dy)
    c, s = math.cos(math.pi / 3), math.sin(math.pi / 3)
    peak = (a[0] + dx * c - dy * s, a[1] + dx * s + dy * c)   # turned by 60 degrees
    for u, v in [(p, a), (a, peak), (peak, b), (b, q)]:
        koch(u, v, depth - 1, points)


def curve(depth):
    points = []
    koch((0.0, 0.0), (1.0, 0.0), depth, points)
    return points + [(1.0, 0.0)]
Listing 22.8. The Koch curve: four recursive calls per segment. code/grade-12/01-recursion/listings/koch.py
The Koch curve at depth 3, from figures/koch_points.py: 43 = 64 segments, 65 points.
The Koch curve at depth 33, from figures/koch_points.py: 43=644^3 = 64 segments, 6565 points.

The naive Fibonacci numbers

The Fibonacci numbers start 0,10, 1 and continue by adding the two before. Written recursively as the definition says, the function is short and extremely slow.

calls = 0


def fib(n):
    """fib(0) = 0, fib(1) = 1, then each is the sum of the two before."""
    global calls
    calls += 1
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)


for n in [5, 10, 15, 20, 25]:
    calls = 0
    value = fib(n)
    print(f"fib({n:2}) = {value:6}   calls: {calls:7}")
Listing 22.9. The definition, as a recursive function, counting its calls. code/grade-12/01-recursion/listings/fib_calls.py
$ python fib_calls.py
fib( 5) =      5   calls:      15
fib(10) =     55   calls:     177
fib(15) =    610   calls:    1973
fib(20) =   6765   calls:   21891
fib(25) =  75025   calls:  242785
Output 22.8. The calls grow much faster than nn: each step of 55 multiplies them by about 1111.
The 15 calls of fib(5). The shaded calls repeat work already done elsewhere in the tree: the whole right subtree fib(3), and a second fib(2). The chapter on dynamic programming removes the repetition.
The 1515 calls of fib(5). The shaded calls repeat work already done elsewhere in the tree: the whole right subtree fib(3), and a second fib(2). The chapter on dynamic programming removes the repetition.

22.6 Exercises

Exercise 22.1 ★

Write what trace_calls.py would print for factorial(3).

Solution

Solution of Exercise 22.1.

factorial(3) called

factorial(2) called

factorial(1) called

factorial(0) called

factorial(0) returns 1

factorial(1) returns 1

factorial(2) returns 2

factorial(3) returns 6

Exercise 22.2 ★

How many moves does hanoi make for 55 disks? Which disk moves at the 1616th move?

Solution

Solution of Exercise 22.2.

25−1=312^5 - 1 = 31 moves. The first 1515 move the four smaller disks to B; the 1616th moves disk 55, the largest, from A to C; the last 1515 bring the four back on top of it.

Exercise 22.3 ★

What does reverse("loop") return, with reverse(s) returning "" for the empty string and otherwise reverse(s[1:]) + s[0]?

Solution

Solution of Exercise 22.3.

reverse("loop") is reverse("oop") + "l", which is reverse("op") + "o" + "l", and so on: "p" + "o" + "o" + "l", that is "pool".

Exercise 22.4 ★

How many frames of sum_list are on the stack at the deepest point of sum_list([4, 8, 15, 16, 23, 42])?

Solution

Solution of Exercise 22.4.

Seven: one call for each length from 66 down to 00, the call on the empty list being the base case at the top. (Below them sits the frame of the code that made the first call.)

Exercise 22.5 ★

Write a recursive count_digits(n), the number of decimal digits of a whole number n≥0n \ge 0.

Solution

Solution of Exercise 22.5.

def count_digits(n):

if n < 10:

return 1

return 1 + count_digits(n // 10)

n // 10 drops the last digit. count_digits(2026) returns 44; count_digits(0) returns 11, since 00 is written with one digit.

Exercise 22.6 ★★

A student writes def total(n): return n + total(n - 1) for 0+1+⋯+n0 + 1 + \dots + n. What happens on total(3)? Correct it.

Solution

Solution of Exercise 22.6.

There is no base case: total(3) calls total(2), total(1), total(0), total(-1), and so on, until Python stops it with RecursionError. Correction: if n == 0: return 0 before the recursive case.

Exercise 22.7 ★★

What does factorial(-1) do? Change the function so that it refuses a negative number at once, with a clear error.

Solution

Solution of Exercise 22.7.

It calls factorial(-2), factorial(-3), …: the base case 00 is never reached, and the run ends with RecursionError, a message that does not name the real mistake. Correction, at the top of the function:

if n < 0:

raise ValueError("factorial of a negative number")

Exercise 22.8 ★★

Write flatten(nested), which returns the numbers of a list of lists, at any depth, in order, in one flat list.

Solution

Solution of Exercise 22.8.

def flatten(nested):

if not isinstance(nested, list):

return [nested]

out = []

for item in nested:

out += flatten(item)

return out

flatten([1, [2, [3, 4]], [], 5]) returns [1, 2, 3, 4, 5].

Exercise 22.9 ★★

Prove by induction that power(x, n) returns xnx^n for every whole number n≥0n \ge 0, and that it stops.

Solution

Solution of Exercise 22.9.

Let P(n)P(n) be “power(x, n) returns xnx^n”. P(0)P(0): the function returns 1=x01 = x^0. If P(n−1)P(n - 1) holds, then power(x, n) returns x×xn−1=xnx \times x^{n-1} = x^n, so P(n)P(n) holds. By induction, P(n)P(n) holds for every n≥0n \ge 0. It stops: the variant nn is a whole number at least 00, decreased by 11 at each call, so after nn calls it is 00, the base case.

Exercise 22.10 ★★

show(n) does nothing for n=0n = 0, and otherwise calls show(n - 1), prints n, and calls show(n - 1) again. What does show(3) print? How many numbers does show(n) print?

Solution

Solution of Exercise 22.10.

1 2 1 3 1 2 1, one per line. show(n) prints p(n)=2p(n−1)+1p(n) = 2p(n - 1) + 1 numbers, with p(0)=0p(0) = 0: the same relation as the towers of Hanoi, so p(n)=2n−1p(n) = 2^n - 1. (It prints exactly the disks moved by hanoi, in order.)

Exercise 22.11 ★★

Write a recursive is_palindrome(s): a string of length at most 11 is a palindrome; a longer one is, when its first and last characters are equal and the string between them is one.

Solution

Solution of Exercise 22.11.

def is_palindrome(s):

if len(s) <= 1:

return True

return s[0] == s[-1] and is_palindrome(s[1:-1])

The variant is the length, decreased by 22 at each call; it ends at 00 or 11.

Exercise 22.12 ★★★

Prove by induction that every solution of the towers of Hanoi with nn disks makes at least 2n−12^n - 1 moves. (Look at the first time the largest disk moves.)

Solution

Solution of Exercise 22.12.

Let P(n)P(n): “every solution for nn disks makes at least 2n−12^n - 1 moves”. P(1)P(1): at least one move, 21−12^1 - 1. Assume P(n−1)P(n - 1) and take a solution for nn disks. The first time the largest disk moves, from A to some peg, the other n−1n - 1 disks are all on the third peg: it cannot sit on any of them, and it leaves A only when nothing is on it. Getting them there from A is a solution for n−1n - 1 disks: at least 2n−1−12^{n-1} - 1 moves, by P(n−1)P(n - 1). The largest disk moves at least once. After its last move, it lies on C and the n−1n - 1 others must come onto it from wherever they are, all on one peg again, since the largest disk could only have moved with all of them elsewhere: at least 2n−1−12^{n-1} - 1 more moves. In all at least 2(2n−1−1)+1=2n−12(2^{n-1} - 1) + 1 = 2^n - 1. By induction, P(n)P(n) holds for every n≥1n \ge 1.

Exercise 22.13 ★★★

Let c(n)c(n) be the number of calls made by fib(n), the first call included. Prove that c(n)=2 fib(n+1)−1c(n) = 2\,\mathrm{fib}(n + 1) - 1, and check it on the output.

Solution

Solution of Exercise 22.13.

fib(0) and fib(1) make one call each: c(0)=c(1)=1c(0) = c(1) = 1, and 2 fib(1)−1=2 fib(2)−1=12\,\mathrm{fib}(1) - 1 = 2\,\mathrm{fib}(2) - 1 = 1. For n≥2n \ge 2, fib(n) makes itself one call plus all the calls of fib(n - 1) and fib(n - 2): c(n)=1+c(n−1)+c(n−2)c(n) = 1 + c(n - 1) + c(n - 2). If the formula holds for n−1n - 1 and n−2n - 2: c(n)=1+2 fib(n)−1+2 fib(n−1)−1=2 fib(n+1)−1c(n) = 1 + 2\,\mathrm{fib}(n) - 1 + 2\,\mathrm{fib}(n - 1) - 1 = 2\,\mathrm{fib}(n + 1) - 1. By induction (on two previous values), it holds for all nn. Check: fib(6)=8\mathrm{fib}(6) = 8, c(5)=15c(5) = 15; fib(26)=121 393\mathrm{fib}(26) = 121\,393, c(25)=242 785c(25) = 242\,785, as printed.

Exercise 22.14 ★★★

Write a recursive subsets(t), which returns the list of all subsets of the list t, each as a list. How many does it return for a list of nn elements? Prove it.

Solution

Solution of Exercise 22.14.

def subsets(t):

if t == []:

return [[]]

rest = subsets(t[1:])

return rest + [[t[0]] + s for s in rest]

The subsets of t are those without t[0], the subsets of the rest, and those with it. If the rest, of n−1n - 1 elements, has 2n−12^{n-1} subsets, t has 2×2n−1=2n2 \times 2^{n-1} = 2^n; the empty list has 1=201 = 2^0. By induction, 2n2^n subsets for nn elements.

Exercise 22.15 ★★★

Write a recursive binary(n), the binary writing of a whole number n≥0n \ge 0 as a string, and prove it correct by induction.

Solution

Solution of Exercise 22.15.

def binary(n):

if n < 2:

return str(n)

return binary(n // 2) + str(n % 2)

Proof, by induction on nn, assuming the result for every smaller number. For n=0n = 0 and n=1n = 1, the writing is the digit itself. For n≥2n \ge 2, n=2q+rn = 2q + r with q=⌊n/2⌋≥1q = \lfloor n/2 \rfloor \ge 1 and r=n mod 2r = n \bmod 2. Since q<nq < n, binary(q) is the binary writing of qq; appending the digit rr multiplies the value by 22 and adds rr: the result is 2q+r=n2q + r = n, with no leading zero since q≥1q \ge 1. binary(37) returns 100101.

22.7 Problem: The Sixty-Four Disks

Problem 22.1

Weekend problem — how long would the priests of the legend need?

The legend of the puzzle speaks of 6464 disks. This problem finds how many moves they need, proves that no one can do better, and turns the number into time.

"""The legend's tower: 64 disks, one move per second."""
from hanoi import hanoi

for n in range(1, 11):                       # check the formula on small towers
    moves = []
    hanoi(n, "A", "C", "B", moves)
    assert len(moves) == 2**n - 1
moves_64 = 2**64 - 1
year = 365.25 * 24 * 3600                    # seconds in a year, on average
print(f"moves for 64 disks: {moves_64:,}")
print(f"seconds in a year: {year:,.0f}")
print(f"years at one move per second: {moves_64 / year:,.0f}")
print(f"about {moves_64 / year / 1e9:.0f} billion years")
Listing 22.10. The count for 6464 disks, with Python’s integers. code/grade-12/01-recursion/listings/sixty_four.py
$ python sixty_four.py
moves for 64 disks: 18,446,744,073,709,551,615
seconds in a year: 31,557,600
years at one move per second: 584,542,046,091
about 585 billion years
Output 22.9. Twenty digits of moves; hundreds of billions of years.

Part I — The recursive solution.

  1. In hanoi, what is the base case? What are the two recursive calls, and on which pegs?
  2. Why does the largest disk never lie on a smaller one in this solution?
  3. Write the moves for n=2n = 2.
  4. How deep does the call stack go for nn disks? Can hanoi(64, ...) overflow the stack?
  5. Why can the program not list the moves for 6464 disks, although its stack is shallow?

Part II — Counting the moves.

  1. Let m(n)m(n) be the number of moves made by hanoi for nn disks. Give m(0)m(0), and m(n)m(n) in terms of m(n−1)m(n - 1).
  2. Compute m(1)m(1) to m(5)m(5) from that relation, and compare with the output of hanoi.py.
  3. How many times does the smallest disk move, for nn disks?
  4. How many times does the largest disk move?

Part III — Proofs.

  1. Prove by induction that m(n)=2n−1m(n) = 2^n - 1.
  2. Prove by induction that every solution makes at least 2n−12^n - 1 moves.
  3. Conclude: the program’s solution uses the fewest moves possible.
  4. What does sixty_four.py check before computing, and why is it not a proof?
  5. Why can 2**64 - 1 be computed exactly, when the toy machine’s numbers stop at 255255?

Part IV — The legend’s time.

  1. How many moves do 6464 disks need? Read the output.
  2. Where does the number of seconds in a year, 31 557 60031\,557\,600, come from?
  3. At one move per second, how many years does the task take?
  4. A machine that makes a billion moves per second: how many years?
  5. At one move per second, how many disks could be moved in 8080 years, a long human life? Find the largest nn whose 2n−12^n - 1 moves fit.
  6. State the result: the number of moves for 6464 disks, and the time at one move per second.
Solution

Solution of Problem 22.1.

1. The base case is n=0n = 0: nothing to move. The calls: n−1n - 1 disks from start to spare (using goal as spare), then n−1n - 1 disks from spare to goal (using start).

2. When the largest disk moves, the n−1n - 1 others are on the spare peg, so its start and goal pegs are empty; every other move belongs to a smaller puzzle in which disks larger than those moved are all at the bottom of their pegs, and can carry any of them.

3. Disk 11: A →\to B; disk 22: A →\to C; disk 11: B →\to C.

4. n+1n + 1 frames of hanoi, from nn down to 00: 6565 for 6464 disks, far below the limit of 10001000.

5. The stack is shallow, but the list of moves would hold 264−12^{64} - 1 entries, more than any memory can hold, and producing them would take the time of Part IV.

6. m(0)=0m(0) = 0 and m(n)=2 m(n−1)+1m(n) = 2\,m(n - 1) + 1.

7. 11, 33, 77, 1515, 3131: as printed.

8. 2n−12^{n-1} times: the smallest disk moves at every other move, starting with the first.

9. Once.

10. m(0)=0=20−1m(0) = 0 = 2^0 - 1. If m(n−1)=2n−1−1m(n - 1) = 2^{n-1} - 1, then m(n)=2(2n−1−1)+1=2n−1m(n) = 2(2^{n-1} - 1) + 1 = 2^n - 1.

11. Exercise 22.12.

12. It makes 2n−12^n - 1 moves, and no solution makes fewer: it is optimal.

13. That the moves are 2n−12^n - 1 for n=1n = 1 to 1010, with an assert. Ten cases checked do not prove the formula for 6464, or for any nn not tried; the induction does.

14. Python’s integers grow as needed (chapter 3); the toy machine’s registers hold one byte.

15. 18 446 744 073 709 551 61518\,446\,744\,073\,709\,551\,615.

16. 365.25×24×3600365.25 \times 24 \times 3600: a year of 365365 days and a quarter, the average over leap years.

17. About 584 542584\,542 million years: 585585 billion, rounded.

18. A billion times fewer: about 585585 years.

19. 8080 years are 2 524 608 0002\,524\,608\,000 seconds. 231−1=2 147 483 6472^{31} - 1 = 2\,147\,483\,647 fits, 232−1=4 294 967 2952^{32} - 1 = 4\,294\,967\,295 does not: 3131 disks.

20. The 6464 disks need 264−1=18 446 744 073 709 551 6152^{64} - 1 = 18\,446\,744\,073\,709\,551\,615 moves, the fewest possible; at one move per second, about 585585 billion years.

Terms defined in this chapter

See all 1050 terms in the glossary