University Computer Science — Year 1 · Bachelor Year 1
12Program 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 of elements or more, the line mid = (low + high) / 2 overflowed, and the search read outside the 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 says what a program must do, a loop invariant says why a loop does it, a variant says why it stops, and tests derived from the specification check the code against it on the cases a proof might have missed.
You already know
An assertion states a condition the program expects to hold at a point, and stops the program when it does not (Chapter 7). A variant is a quantity in a well-founded set that decreases at every iteration (Chapter 11). Binary search finds a value in a sorted 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.
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
The docstring states the specification in words; the assertions check it while the program runs. The postcondition and determines and 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
12.2 Partial and total correctness
Definition 12.2 (Partial correctness, total correctness)
A program is partially correct with respect to a specification if every execution that starts in a state satisfying the precondition and terminates ends in a state satisfying the postcondition. It is totally correct if, moreover, every such execution terminates.
Partial correctness says nothing about the runs that never end: a loop while True: pass is partially correct for every specification. The division loop, run without its precondition, illustrates the difference: with , stays true for ever, and the loop never ends; but whenever it does end, its result satisfies the postcondition, so it is partially correct even then. Total correctness is partial correctness plus termination, proved separately, by a variant: here , which decreases by at each iteration, and only because of the precondition.
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)
- Start from the postcondition, 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 and drop , which is the negation of
r >= b), or replace a constant by a variable (for the maximum of , “ is the maximum of ” with in place of ). - Initialisation: prove that the invariant holds after the code before the loop.
- Preservation: assuming the invariant and the loop condition, prove the invariant after one iteration.
- Conclusion: prove that the invariant and the negation of the loop condition imply the postcondition.
- Termination: find a variant, and prove that it decreases at every iteration.
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
$ python maximum.py
9 -5 3
The 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. For the division, the obligations are short. Initialisation: and give and . Preservation: if and , then and . Conclusion: with at the exit, the postcondition holds. Termination: is a natural number that decreases by .
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. Lomuto’s version scans the slice once, with two indices.
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
$ 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
Proposition 12.5 (Lomuto’s partition is correct)
If , partition(a, lo, hi) terminates, permutes , and returns with and , where is the original .
Proof. The loop runs from to , so it terminates, and the only changes to are swaps: a permutation. Invariant: and . At the start, , both regions are empty. If , only moves: the second region gains . If , swapping and puts at the end of the first region and moves the first element of the second region (if any) to its end; then and move. At the exit, : the slice is on , on , and at . The final swap puts at and the element (if ) at , inside the second region. ∎
Binary search on a half-open interval
The half-open interval , the integers with , is the convenient way to describe a slice: its length is , it is empty when , and and split it without overlap. Binary search keeps such an interval of candidates.
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:]
$ 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
Proposition 12.6 (Binary search is correct)
If is sorted, leftmost(a, x) terminates and returns the least with , or if there is none.
Proof. Invariant: , every element of is , and every element of is . Initially and , and both slices are empty. In an iteration , so : is a valid index, and the interval shrinks whichever branch runs. If , then, being sorted, all of is , and keeps the invariant; otherwise all of is , and keeps it. Variant: , which decreases since and . At the exit : everything before is and everything from on is , so is the least index with , or . ∎
At most iterations run (Exercise 12.9). The midpoint is written rather than : in Python both are correct, but in C the sum of two large int indices overflows (Chapter 2), 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.
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
$ python flag.py
[0, 0, 0, 1, 1, 1, 2, 2, 2] 6 swaps
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 ).
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 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, 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.
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
The library hypothesis generates the sorted lists and the values; the standard module bisect serves as the first oracle, and the postcondition, 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 of elements: tests can show the presence of errors, and proofs their absence under stated assumptions.
Safe use
An assertion that checks an invariant can be expensive and can be disabled (Chapter 7); it must never have a side effect the program relies on. Inputs from users or files are checked by code that reports an error, not by assertions: a violated precondition 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 does it meet? (a) pre ; post divides the result. (b) pre ; post . (c) pre ; post the result is at most . (d) pre ; post the result is a multiple of , at most , and the largest such.
Solution
Solution of Exercise 12.1.
In Python, for the remainder a % b lies in , so is the largest multiple of that is at most . (a) Met. (b) Met, since . (c) Not met: for the remainder lies in , and f(5, -3) returns 6, above . (d) Met, for negative too: Python’s remainder takes the sign of .
Exercise 12.2 ★
Give the values of and at each test of the loop of maximum([3, 9, 2, 9, 4]), and check the invariant at each.
Solution
Solution of Exercise 12.2.
At the five tests, is , , , and , and the loop exits at the last. Each time is the maximum of : of , , , and the whole list.
Exercise 12.3 ★
Does each loop terminate for every natural number ? 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
Solution of Exercise 12.3.
(a) Stops for even , with variant ; for odd it passes 1, then and never stops. (b) Stops: is a variant, halved while . (c) Stops only for (no iteration) and ; from the values are , and from any the loop alternates between an even and an odd number for ever. (d) Stops: since 3 and 7 are coprime, meet every remainder modulo 7; the variant is the least with , at most 6, which drops by one at each iteration.
Exercise 12.4 ★
Predict what the program prints.
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))
Solution
Solution of Exercise 12.4.
0 3 0
1 4 0
In : the first 1 is at 0; 2 would go at the end (3); 0 at the start (0). In : the first 2 is at 1, the 3 at 4; in , 4 is at 0.
Exercise 12.5 ★★
This search uses a closed interval 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.
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
1 -1
stuck: lo=0 hi=0 mid=0 after 20 steps
Solution
Solution of Exercise 12.5.
On a closed interval the variant is the number of candidates, . When , and hi = mid decreases it; but when and , hi = mid changes nothing, and the loop repeats the same state. This happens whenever is absent and the search ends next to a larger element: in , for (), and also for or . The fix is hi = mid - 1, with the invariant “every element of is and every element of is ”: and the list is sorted, so is ; and the variant now decreases in all three branches. The half-open version of Listing 12.4 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 fails, and what happens to the list?
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
[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]
Solution
Solution of Exercise 12.6.
Preservation fails. With a[k] = a[j] the element at , which belongs to the region , is overwritten and lost, and the small stays where it was, inside the region , which is no longer . 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’s two conclusions catches both at once.
Exercise 12.7 ★★
Write rightmost(a, x), which returns the least with in a sorted list, on a half-open interval, with its invariant as a comment. Deduce the number of occurrences of , and test both against bisect.
Solution
Solution of Exercise 12.7.
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
The proof is that of Proposition 12.6, with in place of : if , all of is ; otherwise all of is . The occurrences of are exactly , so their number is the difference, as the output of Listing 12.4 showed for . 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, with the invariant of Listing 12.2 and the variant .
Solution
Solution of Exercise 12.8.
Let . Invariant: , and for every of . Initialisation: , , the maximum of . Preservation: with , if the new is , larger than every element of ; otherwise already; either way is the maximum of , and . Conclusion: at the exit and , so and is the maximum of the whole list. Termination: is a natural number that decreases by one.
Exercise 12.9 ★★
Prove that binary search on elements makes at most iterations, and that the bound is reached.
Solution
Solution of Exercise 12.9.
Let and . After hi = mid the length is ; after lo = mid + 1 it is . So after iterations the length is at most , which is 0 for , since then : the loop has stopped. The bound is reached when is below every element: every step takes hi = mid, and the length goes , which stays positive for values. The test checks the worst case for every .
Exercise 12.10 ★★★
The flag of Listing 12.5 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
Solution of Exercise 12.10.
On 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, 6 swaps where 3 suffice.
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)
Count , the elements of value in the region where belongs. A swap moves at most two elements to their place, and does so only for a pair with and ; take as many such swaps as possible. The misplaced elements left form cycles (or the reverse), in equal numbers 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 , with 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, and prove it totally correct with an invariant relating acc, base and e to and . How many iterations does it make?
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
Solution
Solution of Exercise 12.11.
1594323 1024 1
It computes : , , . Specification: pre , post the result is . Invariant: and . Initially . If is odd, ; if is even, . At the exit and . Variant: , halved at each step. The number of iterations is the number of binary digits of , for , and 0 for : 4 for . 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 with the invariant “ and ”, and proves the conclusion as follows: “at the exit and , so ”. The same student proves that while i != n: i = i + 2 (from ) ends with , with the invariant “ is even”. Which proof is right, which is wrong, and where exactly?
Solution
Solution of Exercise 12.12.
The first proof is right, for : preserves the first part, before the step gives after it, and the exit gives . The second is a correct proof of partial correctness only: at the exit by the loop condition alone, and the invariant “ is even” plays no part. What is missing is termination, and it is false for odd (and negative ), where jumps over for ever. The invariant should be “ is even and ”, which needs the precondition “ even and ”; then 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 is the with . Two programs compute it: bisection on the half-open interval , and Newton’s method on integers, started at . Both are compared with the library’s math.isqrt on twelve values up to , and by a property-based test on random 64-bit values.
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
$ 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
Part I — The specification.
- Show that for each exactly one natural number satisfies .
- Show that the specification can be checked with two multiplications, without computing any square root.
- Why is , computed in floating point, not a correct implementation for 64-bit ? Give the order of magnitude of beyond which
floatcannot even represent every integer. - Give the specification of
isqrt_bisectandisqrt_newtonas precondition and postcondition, counting the returned number of steps. - Write a test oracle for the integer square root that uses only the specification.
- Why do the programs return the step counts with the result?
Part II — Bisection.
- Check that the invariant holds initially.
- Show that it is preserved, and that in every iteration.
- Show that is a variant, and deduce termination.
- Prove the conclusion: at the exit, satisfies the specification.
- Show that the number of iterations is at most , and compare with the table.
- In C with 64-bit unsigned integers, which expressions of
isqrt_bisectcan overflow for ? How would you avoid it?
Part III — Newton’s method on integers.
- Let be the integer square root of . For an integer , show that .
- Show that for , and deduce that the new is at least : the invariant is preserved.
- Show that if , the new is strictly smaller than .
- Deduce that the loop terminates, and that at the exit .
- Why must the case be treated apart?
- Why does the loop test rather than new ?
Part IV — Tests and counts.
- Read the table: for which does bisection reach , and for which does it stay below?
- Newton’s method needs 37 iterations for . Explain why the first iterations roughly halve , and why the last few are fast.
- Suggest a better starting value than and say what must be proved again.
- The property-based test draws at random below . Why does it also check every separately?
- What would the test have caught if
isqrt_newtonreturned with rather than in its loop condition? Check by reasoning on . - State the named result of the problem, Newton’s integer square root is totally correct, with the measured iteration counts against bisection’s.
Solution
Solution of Problem 12.1.
1. Existence: contains 0 and is bounded by ; its largest element has . Uniqueness: if both satisfied it, then and , a contradiction.
2. Compute and and compare them with .
3. A float has a 53-bit significand: above not every integer is representable, and is rounded before the root is taken. For , math.floor(math.sqrt(n)) gives 4 294 967 296, one too many.
4. Precondition: is an integer, . Postcondition: the result is with and 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. and .
8. In an iteration , so . If , lo = mid keeps ; otherwise and hi = mid keeps .
9. is a natural number ( gives ) and decreases strictly, since lies strictly between and ; the loop runs only while it exceeds 1.
10. At the exit , so , and the invariant reads .
11. A step leaves or , so after steps the length is at most , which is 1 once : at most steps. The table reaches the bound except for 16, 17, 99 and , one below.
12. is 0 for ; can exceed ; and overflows once . Start with (the root of a 64-bit number is below it, so holds), compute , and test (for ) instead of .
13. Write with and , and . If is even, ; if is odd, with , so the floor is . Either way it is .
14. . Taking floors, the new is at least . Initially , since for .
15. gives , so , and its floor is below .
16. is a natural number that decreases strictly at each iteration: the loop stops. At the exit , so , the largest number whose square is at most ; with the invariant , .
17. The first step computes n // r with : a division by zero.
18. The values can oscillate between and : for , gives 3, and gives 4, and so on. The test stops at 3.
19. The bound is reached for 0, 1, 2, 15, , , and ; bisection stays one below for 16, 17, 99 and , where the intervals happen to shrink a little faster than half.
20. While is far above , is small beside , and the new is about : from to near takes about 32 steps. Near the error is roughly squared at each step (it becomes about ), so a handful of steps finish: .
21. Start at with the number of binary digits of : since , , so it is at least . 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 : goes , then still holds and stays 4 for ever. The variant fails when : the new equals . The test would never finish: the exhaustive loop hangs at , where stays 1.
24. Newton’s integer square root is totally correct: for every , isqrt_newton(n) terminates and returns the with (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 .