---
title: "Program Correctness"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 12
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/12-program-correctness
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 12 — Program Correctness

A well-known book on programming presented a binary search, proved it correct, and tested it. The code was copied into the standard library of a major programming language, where it ran for about nine years before it failed: on an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of $2^{30}$ elements or more, the line `mid = (low + high) / 2` overflowed, and the search read outside the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array). The proof had assumed integers without limits; the machine had 32-bit ones. Proofs of programs are worth their assumptions, and this chapter teaches how to state them: a [specification](#def-b1-program-correctness-specification) says what a program must do, a [loop invariant](#def-b1-program-correctness-invariant) says why a loop does it, a variant says why it stops, and tests derived from the [specification](#def-b1-program-correctness-specification) check the code against it on the cases a proof might have missed.

**You already know.**

An [assertion](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-assertion) states a condition the program expects to hold at a point, and stops the program when it does not ([Chapter 7](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#ch-b1-c-modules-make-tests)). A variant is a quantity in a [well-founded](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#def-b1-induction-and-termination-well-founded) set that decreases at every iteration ([Chapter 11](https://one-course.com/books/computer-science/3/en/chapter/11-induction-recursion-and-termination#ch-b1-induction-and-termination)). Binary search finds a value in a sorted [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) by halving the part still to search.

## 12.1 Specifications

**Definition 12.1 (Precondition, postcondition, specification).**

A *precondition* is a condition on the inputs, and on the state, that a caller must ensure before calling a function. A *postcondition* is a condition relating the result and the final state to the inputs, which the function guarantees when it returns. The pair is the function’s *specification*: a contract, in which the function owes nothing to a caller who broke the precondition.

```python
def divide(a, b):
    """Precondition: a >= 0 and b > 0.
    Postcondition: returns (q, r) with a == q * b + r and 0 <= r < b."""
    assert a >= 0 and b > 0, "precondition"
    q, r = 0, a
    while r >= b:
        assert a == q * b + r and r >= 0, "invariant"  # holds at each test
        q, r = q + 1, r - b  # the variant r decreases by b > 0
    assert a == q * b + r and 0 <= r < b, "postcondition"
    return q, r
```

***Listing 12.1.** Integer division by repeated subtraction, with its contract checked code/bachelor-1/12-program-correctness/listings/division.py*

The docstring states the [specification](#def-b1-program-correctness-specification) in words; the [assertions](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-assertion) check it while the program runs. The [postcondition](#def-b1-program-correctness-specification) $a = qb + r$ and $0 \leq r < b$ determines $q$ and $r$ completely: it is a definition of integer division, while the loop is one way to compute it.

```
$ python division.py
(3, 2) (0, 0) (0, 4)
still running after 1000 steps: q=1000, r=17
AssertionError: precondition
```

***Output 12.1.** Three divisions; the loop without its [precondition](#def-b1-program-correctness-specification), stopped by a step cap; and the [precondition](#def-b1-program-correctness-specification) refusing $b = 0$.*

## 12.2 Partial and total correctness

**Definition 12.2 (Partial correctness, total correctness).**

A program is *partially correct* with respect to a [specification](#def-b1-program-correctness-specification) if every execution that starts in a state satisfying the [precondition](#def-b1-program-correctness-specification) and *terminates* ends in a state satisfying the [postcondition](#def-b1-program-correctness-specification). It is *totally correct* if, moreover, every such execution terminates.

[Partial correctness](#def-b1-program-correctness-correctness) says nothing about the runs that never end: a loop `while True: pass` is [partially correct](#def-b1-program-correctness-correctness) for every [specification](#def-b1-program-correctness-specification). The division loop, run without its [precondition](#def-b1-program-correctness-specification), illustrates the difference: with $b = 0$, $r \geq b$ stays true for ever, and the loop never ends; but whenever it does end, its result satisfies the [postcondition](#def-b1-program-correctness-specification), so it is [partially correct](#def-b1-program-correctness-correctness) even then. [Total correctness](#def-b1-program-correctness-correctness) is [partial correctness](#def-b1-program-correctness-correctness) plus termination, proved separately, by a variant: here $r$, which decreases by $b > 0$ at each iteration, and only because of the [precondition](#def-b1-program-correctness-specification).

![Three kinds of runs from a state satisfying the precondition. Partial correctness forbids a run that stops in a state violating the postcondition; total correctness also forbids a run that never stops.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-program-correctness/fig-64e28d30bde9.svg)

*Three kinds of runs from a state satisfying the [precondition](#def-b1-program-correctness-specification). [Partial correctness](#def-b1-program-correctness-correctness) forbids a run that stops in a state violating the [postcondition](#def-b1-program-correctness-specification); [total correctness](#def-b1-program-correctness-correctness) also forbids a run that never stops.*

## 12.3 Loop invariants

**Definition 12.3 (Loop invariant).**

A *loop invariant* is a condition on the variables of a loop that holds before the first test of the loop condition and is preserved by each iteration: if it holds and the loop condition is true before an iteration, it holds after it. It therefore holds at every test, and in particular when the loop exits.

**Method 12.4 (Finding and using an invariant).**

1. Start from the [postcondition](#def-b1-program-correctness-specification) , and weaken it into a condition that holds part of the way: *drop a conjunct* that the loop condition will supply at the exit (for division, keep $a = qb + r \wedge r \geq 0$ and drop $r < b$ , which is the negation of `r >= b` ), or *replace a constant by a variable* (for the maximum of $xs$ , “ $m$ is the maximum of $xs[0{:}i]$ ” with $i$ in place of $\text{len}(xs)$ ).
2. *Initialisation* : prove that the invariant holds after the code before the loop.
3. *Preservation* : assuming the invariant and the loop condition, prove the invariant after one iteration.
4. *Conclusion* : prove that the invariant and the negation of the loop condition imply the [postcondition](#def-b1-program-correctness-specification) .
5. *Termination* : find a variant, and prove that it decreases at every iteration.

```python
def maximum(xs):
    """Precondition: xs is not empty. Postcondition: returns m in xs, m >= every x."""
    m, i = xs[0], 1
    while i < len(xs):
        # invariant: m is the maximum of xs[0:i], and 1 <= i <= len(xs)
        assert m in xs[:i] and all(m >= x for x in xs[:i]) and 1 <= i <= len(xs)
        if xs[i] > m:
            m = xs[i]
        i += 1  # variant: len(xs) - i
    return m  # i == len(xs): m is the maximum of xs[0:len(xs)], all of xs
```

***Listing 12.2.** The maximum, with its invariant as an [assertion](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-assertion) code/bachelor-1/12-program-correctness/listings/maximum.py*

```
$ python maximum.py
9 -5 3
```

***Output 12.2.** Three maxima, every invariant check passed.*

The [assertion](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-assertion) turns the invariant into a check that runs at every iteration, which costs time (here it makes the loop quadratic) and is for development and tests only. The proof itself is [Exercise 12.8](#exo-b1-program-correctness-8). For the division, the obligations are short. Initialisation: $q = 0$ and $r = a$ give $a = 0 \cdot b + a$ and $r = a \geq 0$. Preservation: if $a = qb + r$ and $r \geq b$, then $a = (q + 1)b + (r - b)$ and $r - b \geq 0$. Conclusion: with $r < b$ at the exit, the [postcondition](#def-b1-program-correctness-specification) holds. Termination: $r$ is a natural number that decreases by $b \geq 1$.

## 12.4 Proofs for array algorithms

### Partition

Partitioning around a pivot rearranges a slice so that the elements smaller than the pivot come first, then the pivot, then the others; quicksort is built on it in [Chapter 19](https://one-course.com/books/computer-science/3/en/chapter/19-sorting#ch-b1-sorting). Lomuto’s version scans the slice once, with two indices.

```python
def partition(a, lo, hi, trace=False):
    """Precondition: lo < hi. Rearranges a[lo:hi] and returns k with
    a[lo:k] < p, a[k] == p, a[k+1:hi] >= p, where p is the pivot a[hi - 1]."""
    p = a[hi - 1]
    k = lo
    for j in range(lo, hi - 1):
        # invariant: a[lo:k] < p and a[k:j] >= p; a[j:hi-1] not yet seen
        if trace:
            print(f"j={j} k={k} {a[lo:k]} | {a[k:j]} | {a[j:hi - 1]} pivot {p}")
        if a[j] < p:
            a[k], a[j] = a[j], a[k]
            k += 1
    a[k], a[hi - 1] = a[hi - 1], a[k]  # the pivot between the two regions
    return k
```

***Listing 12.3.** Lomuto’s partition code/bachelor-1/12-program-correctness/listings/partition.py*

```
$ python partition.py
j=0 k=0 [] | [] | [7, 2, 9, 4, 1, 8] pivot 5
j=1 k=0 [] | [7] | [2, 9, 4, 1, 8] pivot 5
j=2 k=1 [2] | [7] | [9, 4, 1, 8] pivot 5
j=3 k=1 [2] | [7, 9] | [4, 1, 8] pivot 5
j=4 k=2 [2, 4] | [9, 7] | [1, 8] pivot 5
j=5 k=3 [2, 4, 1] | [7, 9] | [8] pivot 5
result [2, 4, 1, 5, 9, 8, 7] pivot at 3
```

***Output 12.3.** The three regions before each step: smaller, not smaller, not yet seen.*

![The invariant of Lomuto’s partition: a(lo:k) < p and a(k:j) ≥ p, the rest unseen. A step looks at a(j) and extends one of the two regions; when j reaches hi - 1, the pivot is swapped into place k, between them.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-program-correctness/fig-b3f4e2aad9ff.svg)

*The invariant of Lomuto’s partition: $a[lo{:}k] < p$ and $a[k{:}j] \geq p$, the rest unseen. A step looks at $a[j]$ and extends one of the two regions; when $j$ reaches $hi - 1$, the pivot is swapped into place $k$, between them.*

**Proposition 12.5 (Lomuto’s partition is correct).**

If $lo < hi$, `partition(a, lo, hi)` terminates, permutes $a[lo{:}hi]$, and returns $k$ with $a[lo{:}k] < a[k]$ and $a[k + 1{:}hi] \geq a[k]$, where $a[k]$ is the original $a[hi - 1]$.

**Proof.** The loop runs $j$ from $lo$ to $hi - 2$, so it terminates, and the only changes to $a$ are swaps: a permutation. Invariant: $a[lo{:}k] < p$ and $a[k{:}j] \geq p$. At the start, $k = j = lo$, both regions are empty. If $a[j] \geq p$, only $j$ moves: the second region gains $a[j]$. If $a[j] < p$, swapping $a[k]$ and $a[j]$ puts $a[j]$ at the end of the first region and moves the first element of the second region (if any) to its end; then $k$ and $j$ move. At the exit, $j = hi - 1$: the slice is $< p$ on $[lo, k)$, $\geq p$ on $[k, hi - 1)$, and $p$ at $hi - 1$. The final swap puts $p$ at $k$ and the element $a[k] \geq p$ (if $k < hi - 1$) at $hi - 1$, inside the second region. ∎

### Binary search on a half-open interval

The half-open interval $[lo, hi)$, the integers $i$ with $lo \leq i < hi$, is the convenient way to describe a slice: its length is $hi - lo$, it is empty when $lo = hi$, and $[lo, mid)$ and $[mid, hi)$ split it without overlap. Binary search keeps such an interval of candidates.

```python
def leftmost(a, x):
    """Precondition: a sorted. Returns the least i with a[i] >= x (len(a) if none):
    the position of the first x if x is present, where to insert it otherwise."""
    lo, hi = 0, len(a)
    while lo < hi:
        # invariant: a[:lo] < x <= a[hi:], and 0 <= lo <= hi <= len(a)
        mid = lo + (hi - lo) // 2  # lo <= mid < hi
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo  # lo == hi: a[:lo] < x <= a[lo:]
```

***Listing 12.4.** The leftmost position of $x$, on $[lo, hi)$ code/bachelor-1/12-program-correctness/listings/bsearch.py*

```
$ python bsearch.py
x= 3: leftmost 1, found
x= 2: leftmost 0, found
x= 9: leftmost 5, found
x= 5: leftmost 4, absent
x= 1: leftmost 0, absent
x=10: leftmost 6, absent
empty list: 0
```

***Output 12.4.** Present, with duplicates, at both ends, absent inside and outside, and the empty list.*

**Proposition 12.6 (Binary search is correct).**

If $a$ is sorted, `leftmost(a, x)` terminates and returns the least $i$ with $a[i] \geq x$, or $\text{len}(a)$ if there is none.

**Proof.** Invariant: $0 \leq lo \leq hi \leq n$, every element of $a[{:}lo]$ is $< x$, and every element of $a[hi{:}]$ is $\geq
x$. Initially $lo = 0$ and $hi = n$, and both slices are empty. In an iteration $lo < hi$, so $lo \leq mid < hi$: $mid$ is a valid index, and the interval shrinks whichever branch runs. If $a[mid] < x$, then, $a$ being sorted, all of $a[{:}mid + 1]$ is $< x$, and $lo = mid + 1$ keeps the invariant; otherwise all of $a[mid{:}]$ is $\geq x$, and $hi = mid$ keeps it. Variant: $hi - lo$, which decreases since $mid + 1 > lo$ and $mid < hi$. At the exit $lo = hi$: everything before $lo$ is $< x$ and everything from $lo$ on is $\geq x$, so $lo$ is the least index with $a[lo] \geq x$, or $n$. ∎

![The invariant of binary search on (lo, hi): everything left of lo is smaller than x, everything from hi on is at least x, and the answer lies in (lo, hi). Each step moves one end past mid.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-program-correctness/fig-5bb5e820867c.svg)

*The invariant of binary search on $[lo, hi)$: everything left of $lo$ is smaller than $x$, everything from $hi$ on is at least $x$, and the answer lies in $[lo, hi]$. Each step moves one end past $mid$.*

At most $\lfloor \log_2 n \rfloor + 1$ iterations run ([Exercise 12.9](#exo-b1-program-correctness-9)). The midpoint is written $lo + (hi - lo)/2$ rather than $(lo + hi)/2$: in Python both are correct, but in C the sum of two large `int` indices overflows ([Chapter 2](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#ch-b1-c-types-and-control)), which is exactly the failure of the opening story. The difference between the two versions is invisible to the proof unless the proof states that the variables are mathematical integers.

### The three-colour flag

A list holds only the values 0, 1 and 2 (three colours); sort it in one pass, with swaps only. This is the *three-colour flag problem*, also called the Dutch national flag problem. Its invariant has four regions.

```python
def flag(a):
    """Rearranges a so that all 0s come first, then 1s, then 2s; returns the swaps."""
    low, mid, high = 0, 0, len(a)
    swaps = 0
    while mid < high:
        # invariant: a[:low] == 0, a[low:mid] == 1, a[mid:high] unknown, a[high:] == 2
        if a[mid] == 0:
            a[low], a[mid] = a[mid], a[low]
            low, mid, swaps = low + 1, mid + 1, swaps + 1
        elif a[mid] == 1:
            mid += 1
        else:
            high -= 1
            a[mid], a[high] = a[high], a[mid]
            swaps += 1
    return swaps  # mid == high: the unknown region is empty
```

***Listing 12.5.** The three-colour flag in one pass code/bachelor-1/12-program-correctness/listings/flag.py*

```
$ python flag.py
[0, 0, 0, 1, 1, 1, 2, 2, 2] 6 swaps
```

***Output 12.5.** Nine values sorted, with six swaps.*

![The four regions of the three-colour flag and the three cases of a step. Each step shrinks the unknown region by one, so high - mid is a variant; when it is empty, the list is sorted.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-program-correctness/fig-29f60910bbf8.svg)

*The four regions of the three-colour flag and the three cases of a step. Each step shrinks the unknown region by one, so $high - mid$ is a variant; when it is empty, the list is sorted.*

In the case 2, `mid` does not advance: the value swapped in from `high` has not been examined yet. In the case 0, it may advance, because the value swapped out from `low` came from the region of 1s (or is the same element, when $low = mid$).

## 12.5 Testing against the specification

A proof covers every input but rests on assumptions and can contain errors; tests run the real code on the real machine but cover only the inputs they try. The [specification](#def-b1-program-correctness-specification) connects them: it says what any correct output is, so it can judge outputs automatically.

**Definition 12.7 (Test oracle, property-based test).**

A *test oracle* is a procedure that decides whether an output is correct for an input: a check of the [postcondition](#def-b1-program-correctness-specification), or a comparison with a simpler program known to be correct (a brute-force or library version). A *property-based test* states a property that must hold for all inputs of a kind, generates many inputs at random, checks the property on each, and on a failure reports a smallest failing input it can find.

```python
sorted_lists = st.lists(st.integers(-20, 20), max_size=40).map(sorted)


@given(sorted_lists, st.integers(-25, 25))
def test_leftmost_rightmost(a, x):
    assert leftmost(a, x) == bisect.bisect_left(a, x)
    assert rightmost(a, x) == bisect.bisect_right(a, x)
    i = leftmost(a, x)
    assert all(y < x for y in a[:i]) and all(y >= x for y in a[i:])  # the postcondition
```

***Listing 12.6.** Two oracles for binary search: the library and the [postcondition](#def-b1-program-correctness-specification) code/bachelor-1/12-program-correctness/tests/test_bsearch.py*

The library `hypothesis` generates the sorted lists and the values; the standard module `bisect` serves as the first oracle, and the [postcondition](#def-b1-program-correctness-specification), checked element by element, as the second. A test is only as good as its inputs: these lists hold small values, so that duplicates and absent values are frequent, which is where binary searches fail. No test, however many inputs it tries, would have found the overflow of the opening story on a machine with too little memory for an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of $2^{30}$ elements: tests can show the presence of errors, and proofs their absence under stated assumptions.

**Safe use.**

An [assertion](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-assertion) that checks an invariant can be expensive and can be disabled ([Chapter 7](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#ch-b1-c-modules-make-tests)); it must never have a [side effect](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#def-b1-c-types-and-control-side-effect) the program relies on. Inputs from users or files are checked by code that reports an error, not by [assertions](https://one-course.com/books/computer-science/3/en/chapter/7-modular-programs-makefiles-and-tests#def-b1-c-modules-make-tests-assertion): a violated [precondition](#def-b1-program-correctness-specification) at a public boundary is the caller’s error, and the program must say so.

## 12.6 Exercises

**Exercise 12.1 ★.**

`def f(a, b): return a - a % b` is called with integers. Which of these [specifications](#def-b1-program-correctness-specification) does it meet? (a) pre $a \geq 0, b > 0$; post $b$ divides the result. (b) pre $a \geq 0, b > 0$; post $a - b < f(a, b) \leq a$. (c) pre $b
\neq 0$; post the result is at most $a$. (d) pre $b > 0$; post the result is a multiple of $b$, at most $a$, and the largest such.

**Solution of Exercise 12.1.**

In Python, for $b > 0$ the remainder `a % b` lies in $[0, b)$, so $a - (a \bmod b)$ is the largest multiple of $b$ that is at most $a$. (a) Met. (b) Met, since $0 \leq a \bmod b < b$. (c) Not met: for $b < 0$ the remainder lies in $(b, 0]$, and `f(5, -3)` returns 6, above $a$. (d) Met, for negative $a$ too: Python’s remainder takes the sign of $b$.

**Exercise 12.2 ★.**

Give the values of $i$ and $m$ at each test of the loop of `maximum([3, 9, 2, 9, 4])`, and check the invariant at each.

**Solution of Exercise 12.2.**

At the five tests, $(i, m)$ is $(1, 3)$, $(2, 9)$, $(3, 9)$, $(4, 9)$ and $(5, 9)$, and the loop exits at the last. Each time $m$ is the maximum of $xs[0{:}i]$: of $[3]$, $[3, 9]$, $[3, 9, 2]$, $[3, 9, 2, 9]$ and the whole list.

**Exercise 12.3 ★.**

Does each loop terminate for every natural number $n$? Give a variant or a run that does not stop. (a) `while n != 0: n = n - 2`. (b) `while n > 1: n = n // 2`. (c) `while n > 0: n = n - 1 if n % 2 else n + 1`. (d) `while n % 7 != 0: n = n + 3`.

**Solution of Exercise 12.3.**

(a) Stops for even $n$, with variant $n$; for odd $n$ it passes 1, then $-1, -3, \dots$ and never stops. (b) Stops: $n$ is a variant, halved while $n > 1$. (c) Stops only for $n = 0$ (no iteration) and $n = 1$; from $n = 2$ the values are $3, 2, 3, 2, \dots$, and from any $n \geq 2$ the loop alternates between an even and an odd number for ever. (d) Stops: since 3 and 7 are coprime, $n, n + 3, \dots, n + 18$ meet every remainder modulo 7; the variant is the least $k \geq 0$ with $7 \mid n + 3k$, at most 6, which drops by one at each iteration.

**Exercise 12.4 ★.**

Predict what the program prints.

```python
from bsearch import leftmost

print(leftmost([1, 1, 1], 1), leftmost([1, 1, 1], 2), leftmost([1, 1, 1], 0))
print(leftmost([1, 2, 2, 2, 3], 2), leftmost([1, 2, 2, 2, 3], 3), leftmost([4], 4))
```

***Listing 12.7.** Duplicates and the leftmost position code/bachelor-1/12-program-correctness/listings/exo_dups.py*

**Solution of Exercise 12.4.**

```
0 3 0
1 4 0
```

***Output 12.9.** The leftmost positions. Some lines are left out.*

In $[1, 1, 1]$: the first 1 is at 0; 2 would go at the end (3); 0 at the start (0). In $[1, 2, 2, 2, 3]$: the first 2 is at 1, the 3 at 4; in $[4]$, 4 is at 0.

**Exercise 12.5 ★★.**

This search uses a closed interval $[lo, hi]$ but updates it as a half-open one. Find the inputs on which it never stops, explain why with the variant, and correct it with its invariant.

```python
def search(a, x, max_steps=20):
    lo, hi = 0, len(a) - 1
    steps = 0
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == x:
            return mid
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid  # should be mid - 1 on a closed interval
        steps += 1
        if steps == max_steps:
            return f"stuck: lo={lo} hi={hi} mid={mid} after {steps} steps"
    return -1
```

***Listing 12.8.** A search that can loop code/bachelor-1/12-program-correctness/listings/bsearch_bug.py*

```
1 -1
stuck: lo=0 hi=0 mid=0 after 20 steps
```

***Output 12.6.** Two answers, then a step cap. Some lines are left out.*

**Solution of Exercise 12.5.**

On a closed interval the variant is the number of candidates, $hi - lo + 1$. When $lo < hi$, $mid < hi$ and `hi = mid` decreases it; but when $lo = hi = mid$ and $a[mid] > x$, `hi = mid` changes nothing, and the loop repeats the same state. This happens whenever $x$ is absent and the search ends next to a larger element: in $[2, 5, 8]$, for $x = 1$ ($lo = hi = 0$), and also for $x = 3$ or $x = 6$. The fix is `hi = mid - 1`, with the invariant “every element of $a[{:}lo]$ is $< x$ and every element of $a[hi + 1{:}]$ is $> x$”: $a[mid] > x$ and the list is sorted, so $a[mid{:}]$ is $> x$; and the variant $hi - lo + 1$ now decreases in all three branches. The half-open version of [Listing 12.4](#lst-b1-program-correctness-bsearch) avoids mixing the two conventions.

**Exercise 12.6 ★★.**

A student writes the partition with a copy instead of a swap. Which part of the proof of [Proposition 12.5](#prop-b1-program-correctness-partition) fails, and what happens to the list?

```python
def partition_bug(a, lo, hi):
    p = a[hi - 1]
    k = lo
    for j in range(lo, hi - 1):
        if a[j] < p:
            a[k] = a[j]
            k += 1
    a[k], a[hi - 1] = a[hi - 1], a[k]
    return k
```

***Listing 12.9.** A partition with a copy code/bachelor-1/12-program-correctness/listings/exo_partition_bug.py*

```
[2, 4, 1, 5, 1, 8, 4] pivot at 3
sorted: [1, 1, 2, 4, 4, 5, 8] instead of [1, 2, 4, 5, 7, 8, 9]
```

***Output 12.7.** The result. Some lines are left out.*

**Solution of Exercise 12.6.**

Preservation fails. With `a[k] = a[j]` the element at $k$, which belongs to the region $\geq p$, is overwritten and lost, and the small $a[j]$ stays where it was, inside the region $a[k{:}j]$, which is no longer $\geq p$. The result is not a permutation (7 and 9 are lost, 1 and 4 appear twice), and it is not even partitioned: 1 and 4 come after the pivot 5. The test of [Proposition 12.5](#prop-b1-program-correctness-partition)’s two conclusions catches both at once.

**Exercise 12.7 ★★.**

Write `rightmost(a, x)`, which returns the least $i$ with $a[i] > x$ in a sorted list, on a half-open interval, with its invariant as a comment. Deduce the number of occurrences of $x$, and test both against `bisect`.

**Solution of Exercise 12.7.**

```python
def rightmost(a, x):
    """Precondition: a sorted. Returns the least i with a[i] > x (len(a) if none)."""
    lo, hi = 0, len(a)
    while lo < hi:
        # invariant: a[:lo] <= x < a[hi:], and 0 <= lo <= hi <= len(a)
        mid = lo + (hi - lo) // 2
        if a[mid] <= x:
            lo = mid + 1
        else:
            hi = mid
    return lo
```

*One past the last occurrence code/bachelor-1/12-program-correctness/exercises/rightmost.py*

The proof is that of [Proposition 12.6](#prop-b1-program-correctness-bsearch), with $\leq$ in place of $<$: if $a[mid] \leq x$, all of $a[{:}mid + 1]$ is $\leq x$; otherwise all of $a[mid{:}]$ is $> x$. The occurrences of $x$ are exactly $a[\mathit{leftmost}{:}\mathit{rightmost}]$, so their number is the difference, as the output of [Listing 12.4](#lst-b1-program-correctness-bsearch) showed for $x = 3$. The test compares both functions with `bisect_left` and `bisect_right` on random sorted lists with many duplicates.

**Exercise 12.8 ★★.**

Prove that `maximum` is [totally correct](#def-b1-program-correctness-correctness), with the invariant of [Listing 12.2](#lst-b1-program-correctness-maximum) and the variant $\text{len}(xs) - i$.

**Solution of Exercise 12.8.**

Let $n = \text{len}(xs) \geq 1$. Invariant: $1 \leq i \leq n$, $m \in xs[0{:}i]$ and $m \geq x$ for every $x$ of $xs[0{:}i]$. Initialisation: $i = 1$, $m = xs[0]$, the maximum of $[xs[0]]$. Preservation: with $i < n$, if $xs[i] > m$ the new $m$ is $xs[i]$, larger than every element of $xs[0{:}i]$; otherwise $m \geq xs[i]$ already; either way $m$ is the maximum of $xs[0{:}i + 1]$, and $i + 1 \leq n$. Conclusion: at the exit $i \geq n$ and $i \leq n$, so $i = n$ and $m$ is the maximum of the whole list. Termination: $n - i$ is a natural number that decreases by one.

**Exercise 12.9 ★★.**

Prove that binary search on $n \geq 1$ elements makes at most $\lfloor \log_2 n \rfloor + 1$ iterations, and that the bound is reached.

**Solution of Exercise 12.9.**

Let $L = hi - lo \geq 1$ and $mid = lo + \lfloor L/2 \rfloor$. After `hi = mid` the length is $\lfloor L/2 \rfloor$; after `lo = mid + 1` it is $L - \lfloor L/2 \rfloor - 1 = \lceil L/2 \rceil - 1 \leq \lfloor L/2 \rfloor$. So after $k$ iterations the length is at most $\lfloor n/2^k \rfloor$, which is 0 for $k = \lfloor \log_2 n \rfloor + 1$, since then $2^k > n$: the loop has stopped. The bound is reached when $x$ is below every element: every step takes `hi = mid`, and the length goes $n, \lfloor n/2 \rfloor, \lfloor n/4 \rfloor, \dots$, which stays positive for $\lfloor \log_2 n \rfloor + 1$ values. The test checks the worst case for every $n < 300$.

**Exercise 12.10 ★★★.**

The flag of [Listing 12.5](#lst-b1-program-correctness-flag) sorts in one pass, but not with the fewest swaps. Find a list on which it makes more swaps than necessary. Then write `min_swaps(a)`, the least number of swaps that sort a list of 0, 1 and 2, and check it against a search over all orders for lists of up to six values.

**Solution of Exercise 12.10.**

On $[2, 2, 0]$ the flag makes 3 swaps (two of them swap an element with itself), where one swap of the first and last elements sorts the list; on the list of [Output 12.5](#out-b1-program-correctness-flag), 6 swaps where 3 suffice.

```python
def min_swaps(a):
    """c[i][j]: elements of value i lying in the region where value j belongs.
    A pair i <-> j of misplaced elements is fixed by one swap; what remains
    forms cycles of three elements, each fixed by two swaps."""
    bounds = [0, a.count(0), a.count(0) + a.count(1), len(a)]
    c = [[0] * 3 for _ in range(3)]
    for j in range(3):
        for x in a[bounds[j]:bounds[j + 1]]:
            c[x][j] += 1
    pairs = sum(min(c[i][j], c[j][i]) for i in range(3) for j in range(i + 1, 3))
    left = sum(c[i][j] for i in range(3) for j in range(3) if i != j) - 2 * pairs
    return pairs + 2 * (left // 3)
```

*The fewest swaps code/bachelor-1/12-program-correctness/exercises/min_swaps.py*

Count $c[i][j]$, the elements of value $i$ in the region where $j$ belongs. A swap moves at most two elements to their place, and does so only for a pair $i \leftrightarrow j$ with $c[i][j] > 0$ and $c[j][i] > 0$; take as many such swaps as possible. The misplaced elements left form cycles $0 \to 1 \to 2 \to 0$ (or the reverse), in equal numbers $t$ in each of the three counts, and a cycle of three needs two swaps, each placing at most one element beyond the pairs. The minimum is $\text{pairs} + 2t$, with $3t$ the elements left. The test compares it with a breadth-first search over all orders reached by swaps, for every list of 0, 1 and 2 of length at most 6, and checks that the flag never does better.

**Exercise 12.11 ★★★.**

Find what this function computes, state its [specification](#def-b1-program-correctness-specification), and prove it [totally correct](#def-b1-program-correctness-correctness) with an invariant relating `acc`, `base` and `e` to $x$ and $n$. How many iterations does it make?

```python
def mystery(x, n):
    """Precondition: n >= 0."""
    acc, base, e = 1, x, n
    while e > 0:
        if e % 2 == 1:
            acc = acc * base
        base = base * base
        e = e // 2
    return acc
```

***Listing 12.10.** A loop to understand code/bachelor-1/12-program-correctness/listings/exo_mystery.py*

**Solution of Exercise 12.11.**

```
1594323 1024 1
```

***Output 12.10.** Three values. Some lines are left out.*

It computes $x^n$: $3^{13} = 1\,594\,323$, $2^{10} = 1024$, $7^0 = 1$. [Specification](#def-b1-program-correctness-specification): pre $n \geq 0$, post the result is $x^n$. Invariant: $\mathit{acc} \cdot \mathit{base}^e = x^n$ and $e \geq 0$. Initially $1 \cdot x^n$. If $e$ is odd, $\mathit{acc} \cdot \mathit{base} \cdot (\mathit{base}^2)^{(e - 1)/2} = \mathit{acc} \cdot \mathit{base}^e$; if $e$ is even, $\mathit{acc} \cdot (\mathit{base}^2)^{e/2} = \mathit{acc} \cdot \mathit{base}^e$. At the exit $e = 0$ and $\mathit{acc} = x^n$. Variant: $e$, halved at each step. The number of iterations is the number of binary digits of $n$, $\lfloor \log_2 n \rfloor + 1$ for $n \geq 1$, and 0 for $n = 0$: 4 for $n = 13$. The test compares with `x ** n`.

**Exercise 12.12 ★★★.**

A student proves that the loop `s = 0; i = 0; while i < n: i = i + 1; s = s + i` computes $s = n(n + 1)/2$ with the invariant “$s = i(i + 1)/2$ and $i \leq n$”, and proves the conclusion as follows: “at the exit $i \leq n$ and $i \geq n$, so $i = n$”. The same student proves that `while i != n: i = i + 2` (from $i = 0$) ends with $i = n$, with the invariant “$i$ is even”. Which proof is right, which is wrong, and where exactly?

**Solution of Exercise 12.12.**

The first proof is right, for $n \geq 0$: $s + i + 1 = (i + 1)(i + 2)/2$ preserves the first part, $i < n$ before the step gives $i + 1 \leq n$ after it, and the exit gives $i = n$. The second is a correct proof of *partial* correctness only: at the exit $i = n$ by the loop condition alone, and the invariant “$i$ is even” plays no part. What is missing is termination, and it is false for odd $n$ (and negative $n$), where $i$ jumps over $n$ for ever. The invariant should be “$i$ is even and $i \leq n$”, which needs the [precondition](#def-b1-program-correctness-specification) “$n$ even and $n \geq 0$”; then $n - i$ is a variant.

## 12.7 Problem: The square root that never lies

**Problem 12.1.**

Weekend problem — The square root that never lies

The integer square root of a natural number $n$ is the $r$ with $r^2 \leq n < (r + 1)^2$. Two programs compute it: bisection on the half-open interval $[0, n + 1)$, and Newton’s method on integers, started at $n$. Both are compared with the library’s `math.isqrt` on twelve values up to $2^{64} - 1$, and by a [property-based test](#def-b1-program-correctness-oracle) on random 64-bit values.

```python
def isqrt_bisect(n):
    lo, hi = 0, n + 1  # invariant: lo * lo <= n < hi * hi
    steps = 0
    while hi - lo > 1:  # variant: hi - lo
        mid = (lo + hi) // 2  # lo < mid < hi
        if mid * mid <= n:
            lo = mid
        else:
            hi = mid
        steps += 1
    return lo, steps


def isqrt_newton(n):
    if n == 0:
        return 0, 0
    r = n  # invariant: r >= the integer square root of n
    steps = 0
    while r * r > n:  # variant: r, which decreases strictly
        r = (r + n // r) // 2
        steps += 1
    return r, steps
```

***Listing 12.11.** Two integer square roots code/bachelor-1/12-program-correctness/listings/isqrt.py*

```
$ python isqrt.py
                     n        root bisection ceil(log2(n+1)) Newton
                     0           0         0               0      0
                     1           1         1               1      0
                     2           1         2               2      1
                    15           3         4               4      3
                    16           4         4               5      3
                    17           4         4               5      3
                    99           9         6               7      5
               1000000        1000        20              20     12
            4294967295       65535        32              32     20
            4294967296       65536        32              33     19
   1000000000000000000  1000000000        60              60     34
  18446744073709551615  4294967295        64              64     37
```

***Output 12.8.** Equal roots, and the iterations of each method.*

**Part I — The specification.**

1. Show that for each $n \geq 0$ exactly one natural number $r$ satisfies $r^2 \leq n < (r + 1)^2$ .
2. Show that the [specification](#def-b1-program-correctness-specification) can be checked with two multiplications, without computing any square root.
3. Why is $\lfloor \sqrt{n} \rfloor$ , computed in floating point, not a correct implementation for 64-bit $n$ ? Give the order of magnitude of $n$ beyond which `float` cannot even represent every integer.
4. Give the [specification](#def-b1-program-correctness-specification) of `isqrt_bisect` and `isqrt_newton` as [precondition](#def-b1-program-correctness-specification) and [postcondition](#def-b1-program-correctness-specification) , counting the returned number of steps.
5. Write a [test oracle](#def-b1-program-correctness-oracle) for the integer square root that uses only the [specification](#def-b1-program-correctness-specification) .
6. Why do the programs return the step counts with the result?

**Part II — Bisection.**

7. Check that the invariant $lo^2 \leq n < hi^2$ holds initially.
8. Show that it is preserved, and that $lo < mid < hi$ in every iteration.
9. Show that $hi - lo$ is a variant, and deduce termination.
10. Prove the conclusion: at the exit, $lo$ satisfies the [specification](#def-b1-program-correctness-specification) .
11. Show that the number of iterations is at most $\lceil \log_2 (n + 1) \rceil$ , and compare with the table.
12. In C with 64-bit unsigned integers, which expressions of `isqrt_bisect` can overflow for $n = 2^{64} - 1$ ? How would you avoid it?

**Part III — Newton’s method on integers.**

13. Let $s$ be the integer square root of $n \geq 1$ . For an integer $r \geq 1$ , show that $\lfloor (r + \lfloor n/r \rfloor)/2 \rfloor = \lfloor (r + n/r)/2 \rfloor$ .
14. Show that $(r + n/r)/2 \geq \sqrt{n}$ for $r > 0$ , and deduce that the new $r$ is at least $s$ : the invariant $r \geq s$ is preserved.
15. Show that if $r^2 > n$ , the new $r$ is strictly smaller than $r$ .
16. Deduce that the loop terminates, and that at the exit $r = s$ .
17. Why must the case $n = 0$ be treated apart?
18. Why does the loop test $r^2 > n$ rather than $r \neq$ new $r$ ?

**Part IV — Tests and counts.**

19. Read the table: for which $n$ does bisection reach $\lceil \log_2 (n + 1) \rceil$ , and for which does it stay below?
20. Newton’s method needs 37 iterations for $2^{64} - 1$ . Explain why the first iterations roughly halve $r$ , and why the last few are fast.
21. Suggest a better starting value than $n$ and say what must be proved again.
22. The [property-based test](#def-b1-program-correctness-oracle) draws $n$ at random below $2^{64}$ . Why does it also check every $n < 2000$ separately?
23. What would the test have caught if `isqrt_newton` returned $r$ with $r^2 \geq n$ rather than $r^2 > n$ in its loop condition? Check by reasoning on $n = 16$ .
24. State the named result of the problem, *Newton’s integer square root is [totally correct](#def-b1-program-correctness-correctness)* , with the measured iteration counts against bisection’s.

**Solution of Problem 12.1.**

**1.** Existence: $\{r \in \mathbb{N} : r^2 \leq n\}$ contains 0 and is bounded by $n + 1$; its largest element $r$ has $(r + 1)^2 > n$. Uniqueness: if $r < r'$ both satisfied it, then $r + 1 \leq r'$ and $(r + 1)^2 \leq r'^2 \leq
n$, a contradiction.

**2.** Compute $r \cdot r$ and $(r + 1) \cdot (r + 1)$ and compare them with $n$.

**3.** A `float` has a 53-bit significand: above $2^{53} \approx 9 \times 10^{15}$ not every integer is representable, and $n$ is rounded before the root is taken. For $n = 2^{64} - 1$, `math.floor(math.sqrt(n))` gives 4 294 967 296, one too many.

**4.** [Precondition](#def-b1-program-correctness-specification): $n$ is an integer, $n \geq 0$. [Postcondition](#def-b1-program-correctness-specification): the result is $(r, k)$ with $r^2 \leq n < (r +
1)^2$ and $k$ the number of iterations made.

**5.** `assert r * r <= n < (r + 1) * (r + 1)`, which needs neither program nor library.

**6.** To compare the methods in Part IV; the test bounds them as well.

**7.** $0^2 = 0 \leq n$ and $n < (n + 1)^2$.

**8.** In an iteration $hi \geq lo + 2$, so $lo + 1 \leq mid \leq hi - 1$. If $mid^2 \leq n$, `lo = mid` keeps $lo^2 \leq n$; otherwise $n < mid^2$ and `hi = mid` keeps $n < hi^2$.

**9.** $hi - lo$ is a natural number ($lo^2 \leq n < hi^2$ gives $lo < hi$) and decreases strictly, since $mid$ lies strictly between $lo$ and $hi$; the loop runs only while it exceeds 1.

**10.** At the exit $lo < hi \leq lo + 1$, so $hi = lo + 1$, and the invariant reads $lo^2 \leq n < (lo + 1)^2$.

**11.** A step leaves $mid - lo = \lfloor L/2 \rfloor$ or $hi - mid = \lceil L/2 \rceil$, so after $k$ steps the length is at most $\lceil (n + 1)/2^k \rceil$, which is 1 once $2^k \geq n + 1$: at most $\lceil \log_2(n + 1) \rceil$ steps. The table reaches the bound except for 16, 17, 99 and $2^{32}$, one below.

**12.** $n + 1$ is 0 for $n = 2^{64} - 1$; $lo + hi$ can exceed $2^{64}$; and $mid \cdot mid$ overflows once $mid
\geq 2^{32}$. Start with $hi = 2^{32}$ (the root of a 64-bit number is below it, so $n < hi^2$ holds), compute $mid = lo
+ (hi - lo)/2$, and test $mid \leq n / mid$ (for $mid \geq 1$) instead of $mid^2 \leq n$.

**13.** Write $n/r = q + f$ with $q = \lfloor n/r \rfloor$ and $0 \leq f < 1$, and $m = r + q$. If $m$ is even, $\lfloor (m + f)/2 \rfloor = m/2$; if $m$ is odd, $(m + f)/2 = (m - 1)/2 + (1 + f)/2$ with $(1 + f)/2 < 1$, so the floor is $(m - 1)/2$. Either way it is $\lfloor m/2 \rfloor$.

**14.** $(r + n/r)/2 - \sqrt{n} = (\sqrt{r} - \sqrt{n/r})^2/2 \geq 0$. Taking floors, the new $r$ is at least $\lfloor \sqrt{n} \rfloor = s$. Initially $r = n \geq s$, since $s \leq s^2 \leq n$ for $s \geq 1$.

**15.** $r^2 > n$ gives $n/r < r$, so $(r + n/r)/2 < r$, and its floor is below $r$.

**16.** $r$ is a natural number that decreases strictly at each iteration: the loop stops. At the exit $r^2 \leq
n$, so $r \leq s$, the largest number whose square is at most $n$; with the invariant $r \geq s$, $r = s$.

**17.** The first step computes `n // r` with $r = n = 0$: a division by zero.

**18.** The values can oscillate between $s$ and $s + 1$: for $n = 15$, $r = 4$ gives 3, and $r = 3$ gives 4, and so on. The test $r^2 > n$ stops at 3.

**19.** The bound is reached for 0, 1, 2, 15, $10^6$, $2^{32} - 1$, $10^{18}$ and $2^{64} - 1$; bisection stays one below for 16, 17, 99 and $2^{32}$, where the intervals happen to shrink a little faster than half.

**20.** While $r$ is far above $\sqrt{n}$, $n/r$ is small beside $r$, and the new $r$ is about $r/2$: from $2^{64}$ to near $2^{32}$ takes about 32 steps. Near $\sqrt{n}$ the error is roughly squared at each step (it becomes about $e^2/(2r)$), so a handful of steps finish: $32 + 5 = 37$.

**21.** Start at $2^{\lceil b/2 \rceil}$ with $b$ the number of binary digits of $n$: since $n < 2^b$, $\sqrt{n} <
2^{b/2}$, so it is at least $s$. Only the initialisation of the invariant must be proved again; preservation, conclusion and termination do not depend on the start.

**22.** Random 64-bit values almost never land on perfect squares, their neighbours or tiny values, where the boundary errors live; the exhaustive check below 2000 covers them all.

**23.** For $n = 16$: $r$ goes $16, 8, 5, 4$, then $4 \cdot 4 \geq 16$ still holds and $r$ stays 4 for ever. The variant fails when $r^2 = n$: the new $r$ equals $r$. The test would never finish: the exhaustive loop hangs at $n = 1$, where $r = 1$ stays 1.

**24.** *Newton’s integer square root is [totally correct](#def-b1-program-correctness-correctness)*: for every $n \geq 0$, `isqrt_newton(n)` terminates and returns the $r$ with $r^2 \leq n < (r + 1)^2$ (questions 13–16). On the table it needs 0, 0, 1, 3, 3, 3, 5, 12, 20, 19, 34 and 37 iterations, against bisection’s 0, 1, 2, 4, 4, 4, 6, 20, 32, 32, 60 and 64, which never exceed $\lceil \log_2(n + 1) \rceil$.
