---
title: "Recursion"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 22
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/22-recursion
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 22 — Recursion

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](https://one-course.com/books/computer-science/2/en/chapter/16-proving-algorithms-correct#ch-g11-proving-algorithms-correct)). A proof by induction shows a property for $0$, then for $n + 1$ whenever it holds for $n$ (the mathematics book, grade 12). Folders and paths (chapter [14](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#ch-g11-os-and-command-line)).

## 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](#def-g12-recursion-recursion) 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 \times 2 \times \dots \times n$, with $0! = 1$, satisfies $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 $x^n = x \times x^{n-1}$.

```python
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](#def-g12-recursion-recursion), each with a [base case](#def-g12-recursion-base-case) and a [recursive case](#def-g12-recursion-base-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!$ has $26$ digits.*

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

```python
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](#def-g12-recursion-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](#def-g12-recursion-call-stack), and do not overwrite one another. This is the stack of the toy machine’s `CALL` and `RET` (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)), 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-recursion/fig-d21fa93f92f0.svg)

*The [call stack](#def-g12-recursion-call-stack) of `factorial(4)` at its deepest point: six [frames](#def-g12-recursion-call-stack), the [base case](#def-g12-recursion-base-case) on top. Each [frame](#def-g12-recursion-call-stack) keeps its own `n` until the call above it returns.*

The stack has a limit. A function that never reaches a [base case](#def-g12-recursion-base-case), or reaches it too deep, fills the stack; Python stops it with `RecursionError` before the memory is exhausted.

```python
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](#def-g12-recursion-recursion) $500$ deep, then the same with the limit lowered to $100$. 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 $1000$ [frames](#def-g12-recursion-call-stack) in this run; lowered below $500$, 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](#def-g12-recursion-recursion) is proved correct by induction on the size of its input: the [base case](#def-g12-recursion-base-case) is checked directly, and the [recursive case](#def-g12-recursion-base-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)$ : “ `f(n)` returns the right value”. Check $P$ on the [base cases](#def-g12-recursion-base-case) . Assume $P$ for the smaller inputs the [recursive case](#def-g12-recursion-base-case) calls, and deduce it for $n$ .
2. *Termination.* Find a variant: a whole number, computed from the arguments, that is at least $0$ and strictly smaller at each recursive call. The calls then cannot go on forever.

For `factorial`: $P(n)$ is “`factorial(n)` returns $n!$”. $P(0)$ holds, since it returns $1 = 0!$. If $P(n - 1)$ holds, then `factorial(n)` returns $n \times (n - 1)! = n!$. By induction, $P(n)$ holds for every $n \ge 0$. The variant is $n$ itself: a whole number, decreased by $1$ at each call, which reaches the [base case](#def-g12-recursion-base-case) $0$. For a negative $n$ 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](#def-g12-recursion-recursion) cannot.

```python
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 $3000$ the [recursion](#def-g12-recursion-recursion) runs out of stack, the loop does not.*

[Recursion](#def-g12-recursion-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.

```python
"""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.*

```python
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 = 89$; a number alone is its own sum, an empty list sums to $0$.*

## 22.5 Three classics

### The towers of Hanoi

Three pegs, A, B and C; on A, $n$ 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 - 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-recursion/img-32b7425e7989.jpg)

*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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-recursion/fig-cb0e6c9b5f6d.svg)

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

```python
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 $20$.*

**History — A puzzle sold with a legend.**

The puzzle was published in Paris in $1883$ 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, $64$ 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](#def-g12-recursion-recursion) computes the points; depth $0$ is the segment itself.

```python
"""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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-recursion/fig-b8024619f736.svg)

*The Koch curve at depth $3$, from `figures/koch_points.py`: $4^3 = 64$ segments, $65$ points.*

### The naive Fibonacci numbers

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

```python
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](#def-g12-recursion-recursion), 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 $n$: each step of $5$ multiplies them by about $11$.*

![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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-recursion/fig-fcbe16dd5b90.svg)

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

## 22.6 Exercises

**Exercise 22.1 ★.**

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

**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 $5$ disks? Which disk moves at the $16$th move?

**Solution of Exercise 22.2.**

$2^5 - 1 = 31$ moves. The first $15$ move the four smaller disks to B; the $16$th moves disk $5$, the largest, from A to C; the last $15$ 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 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](#def-g12-recursion-call-stack) of `sum_list` are on the stack at the deepest point of `sum_list([4, 8, 15, 16, 23, 42])`?

**Solution of Exercise 22.4.**

Seven: one call for each length from $6$ down to $0$, the call on the empty list being the [base case](#def-g12-recursion-base-case) at the top. (Below them sits the [frame](#def-g12-recursion-call-stack) 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 \ge 0$.

**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 $4$; `count_digits(0)` returns $1$, since $0$ is written with one digit.

**Exercise 22.6 ★★.**

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

**Solution of Exercise 22.6.**

There is no [base case](#def-g12-recursion-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](#def-g12-recursion-base-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 of Exercise 22.7.**

It calls `factorial(-2)`, `factorial(-3)`, …: the [base case](#def-g12-recursion-base-case) $0$ 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 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 $x^n$ for every whole number $n \ge 0$, and that it stops.

**Solution of Exercise 22.9.**

Let $P(n)$ be “`power(x, n)` returns $x^n$”. $P(0)$: the function returns $1 = x^0$. If $P(n - 1)$ holds, then `power(x, n)` returns $x \times x^{n-1} = x^n$, so $P(n)$ holds. By induction, $P(n)$ holds for every $n \ge 0$. It stops: the variant $n$ is a whole number at least $0$, decreased by $1$ at each call, so after $n$ calls it is $0$, the [base case](#def-g12-recursion-base-case).

**Exercise 22.10 ★★.**

`show(n)` does nothing for $n = 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 of Exercise 22.10.**

`1 2 1 3 1 2 1`, one per line. `show(n)` prints $p(n) = 2p(n - 1) + 1$ numbers, with $p(0) = 0$: the same relation as the towers of Hanoi, so $p(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 $1$ is a palindrome; a longer one is, when its first and last characters are equal and the string between them is one.

**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 $2$ at each call; it ends at $0$ or $1$.

**Exercise 22.12 ★★★.**

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

**Solution of Exercise 22.12.**

Let $P(n)$: “every solution for $n$ disks makes at least $2^n - 1$ moves”. $P(1)$: at least one move, $2^1 - 1$. Assume $P(n - 1)$ and take a solution for $n$ disks. The first time the largest disk moves, from A to some peg, the other $n - 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 - 1$ disks: at least $2^{n-1} - 1$ moves, by $P(n - 1)$. The largest disk moves at least once. After its last move, it lies on C and the $n - 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 $2^{n-1} - 1$ more moves. In all at least $2(2^{n-1} - 1) + 1 = 2^n - 1$. By induction, $P(n)$ holds for every $n \ge 1$.

**Exercise 22.13 ★★★.**

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

**Solution of Exercise 22.13.**

`fib(0)` and `fib(1)` make one call each: $c(0) = c(1) = 1$, and $2\,\mathrm{fib}(1) - 1 = 2\,\mathrm{fib}(2)
- 1 = 1$. For $n \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)$. If the formula holds for $n - 1$ and $n - 2$: $c(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 $n$. Check: $\mathrm{fib}(6) = 8$, $c(5) = 15$; $\mathrm{fib}(26) = 121\,393$, $c(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 $n$ elements? Prove it.

**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 - 1$ elements, has $2^{n-1}$ subsets, `t` has $2 \times 2^{n-1} = 2^n$; the empty list has $1 = 2^0$. By induction, $2^n$ subsets for $n$ elements.

**Exercise 22.15 ★★★.**

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

**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 $n$, assuming the result for every smaller number. For $n = 0$ and $n = 1$, the writing is the digit itself. For $n \ge 2$, $n = 2q + r$ with $q = \lfloor n/2 \rfloor \ge 1$ and $r = n \bmod 2$. Since $q < n$, `binary(q)` is the binary writing of $q$; appending the digit $r$ multiplies the value by $2$ and adds $r$: the result is $2q + r = n$, with no leading zero since $q \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 $64$ disks. This problem finds how many moves they need, proves that no one can do better, and turns the number into time.

```python
"""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 $64$ 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](#def-g12-recursion-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 = 2$ .
4. How deep does the [call stack](#def-g12-recursion-call-stack) go for $n$ disks? Can `hanoi(64, ...)` overflow the stack?
5. Why can the program not list the moves for $64$ disks, although its stack is shallow?

**Part II — Counting the moves.**

6. Let $m(n)$ be the number of moves made by `hanoi` for $n$ disks. Give $m(0)$ , and $m(n)$ in terms of $m(n - 1)$ .
7. Compute $m(1)$ to $m(5)$ from that relation, and compare with the output of `hanoi.py` .
8. How many times does the smallest disk move, for $n$ disks?
9. How many times does the largest disk move?

**Part III — Proofs.**

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

**Part IV — The legend’s time.**

15. How many moves do $64$ disks need? Read the output.
16. Where does the number of seconds in a year, $31\,557\,600$ , come from?
17. At one move per second, how many years does the task take?
18. A machine that makes a billion moves per second: how many years?
19. At one move per second, how many disks could be moved in $80$ years, a long human life? Find the largest $n$ whose $2^n - 1$ moves fit.
20. State the result: the number of moves for $64$ disks, and the time at one move per second.

**Solution of Problem 22.1.**

**1.** The [base case](#def-g12-recursion-base-case) is $n = 0$: nothing to move. The calls: $n - 1$ disks from `start` to `spare` (using `goal` as spare), then $n - 1$ disks from `spare` to `goal` (using `start`).

**2.** When the largest disk moves, the $n - 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 $1$: A $\to$ B; disk $2$: A $\to$ C; disk $1$: B $\to$ C.

**4.** $n + 1$ [frames](#def-g12-recursion-call-stack) of `hanoi`, from $n$ down to $0$: $65$ for $64$ disks, far below the limit of $1000$.

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

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

**7.** $1$, $3$, $7$, $15$, $31$: as printed.

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

**9.** Once.

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

**11.** Exercise [22.12](#exo-g12-recursion-12).

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

**13.** That the moves are $2^n - 1$ for $n = 1$ to $10$, with an `assert`. Ten cases checked do not prove the formula for $64$, or for any $n$ not tried; the induction does.

**14.** Python’s integers grow as needed (chapter [3](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#ch-g10-machine-integers)); the toy machine’s registers hold one byte.

**15.** $18\,446\,744\,073\,709\,551\,615$.

**16.** $365.25 \times 24 \times 3600$: a year of $365$ days and a quarter, the average over leap years.

**17.** About $584\,542$ million years: $585$ billion, rounded.

**18.** A billion times fewer: about $585$ years.

**19.** $80$ years are $2\,524\,608\,000$ seconds. $2^{31} - 1 = 2\,147\,483\,647$ fits, $2^{32} - 1 =
4\,294\,967\,295$ does not: $31$ disks.

**20.** **The $64$ disks need $2^{64} - 1 = 18\,446\,744\,073\,709\,551\,615$ moves**, the fewest possible; **at one move per second, about $585$ billion years**.
