Writing Recurrences
A loop's cost is a sum: add up what each iteration does. A recursive procedure's cost refers to itself, because part of the work happens inside calls on smaller inputs. The natural description is then a recurrence, an equation that gives in terms of on smaller sizes. Before any recurrence can be solved it has to be written down correctly, and that is the skill this lesson trains.
The Recurrences lesson in Discrete Mathematics solves several recurrences by "plug and chug". Here the focus is the step before: reading a recursive program and producing the right equation.
The recipe
Look at one call of the procedure on an input of size , and sort its work into three piles.
- Recursive calls. How many are there, and on inputs of what size? If there are calls, each on size about , they contribute .
- Everything else. The work done in this call outside the recursive calls: splitting the input, combining results, loops, copying. Call it .
- Base case. For which small sizes does the procedure stop recursing, and what does it cost there? Usually a constant.
That gives the general divide-and-conquer form
Two warnings. First, and are separate numbers: counts calls, says how fast the size shrinks, and nothing forces . Second, must measure one consistent quantity, such as comparisons, multiplications or total steps. Mixing them gives an equation that describes nothing.
Example 1: binary search
Recursive binary search on the half-open range of a sorted array:
SEARCH(a, x, lo, hi)
1 if lo >= hi
2 return NOT-FOUND
3 mid = floor((lo + hi) / 2)
4 if a[mid] == x return mid
5 if a[mid] < x return SEARCH(a, x, mid + 1, hi)
6 else return SEARCH(a, x, lo, mid)With elements, the left range has elements and the right range has , never more. Each call makes one recursive call and does a constant amount of other work, so the worst-case number of probes (array reads on line 4) is
Its solution is for . The best way to trust a recurrence is to test it against the program: count the probes for every possible target, keep the maximum, and compare.
from functools import lru_cache
import math
def search(a, x, lo, hi, probes):
if lo >= hi:
return -1
probes[0] += 1
mid = (lo + hi) // 2
if a[mid] == x:
return mid
if a[mid] < x:
return search(a, x, mid + 1, hi, probes)
return search(a, x, lo, mid, probes)
@lru_cache(None)
def P(n):
return 0 if n == 0 else P(n // 2) + 1
print(" n measured P(n) floor(lg n)+1")
for n in [1, 2, 3, 7, 8, 100, 1000, 1024]:
a = list(range(0, 2 * n, 2)) # even numbers, so odd targets miss
worst = 0
for x in range(-1, 2 * n + 1):
probes = [0]
search(a, x, 0, n, probes)
worst = max(worst, probes[0])
print(f"{n:4} {worst:8} {P(n):4} {math.floor(math.log2(n)) + 1:13}") n measured P(n) floor(lg n)+1
1 1 1 1
2 2 2 2
3 2 2 2
7 3 3 3
8 4 4 4
100 7 7 7
1000 10 10 10
1024 11 11 11
In C++
The same check in C++. std::bit_width(n), the number of binary digits of , gives without floating point:
#include <algorithm>
#include <bit>
#include <cstdio>
#include <vector>
using namespace std;
int search(const vector<int>& a, int x, int lo, int hi, int& probes) {
if (lo >= hi) return -1;
probes++;
int mid = (lo + hi) / 2;
if (a[mid] == x) return mid;
if (a[mid] < x) return search(a, x, mid + 1, hi, probes);
return search(a, x, lo, mid, probes);
}
int P(int n) { // the recurrence, evaluated directly
return n == 0 ? 0 : P(n / 2) + 1;
}
int main() {
printf(" n measured P(n) floor(lg n)+1\n");
for (int n : {1, 2, 3, 7, 8, 100, 1000, 1024}) {
vector<int> a(n);
for (int i = 0; i < n; i++) a[i] = 2 * i; // even numbers, so odd targets miss
int worst = 0;
for (int x = -1; x <= 2 * n; x++) {
int probes = 0;
search(a, x, 0, n, probes);
worst = max(worst, probes);
}
// bit_width(n) is the number of binary digits of n, which is floor(lg n) + 1
printf("%4d %8d %4d %13d\n", n, worst, P(n), (int)bit_width(unsigned(n)));
}
} n measured P(n) floor(lg n)+1
1 1 1 1
2 2 2 2
3 2 2 2
7 3 3 3
8 4 4 4
100 7 7 7
1000 10 10 10
1024 11 11 11
The three columns agree for every size, including the awkward ones like 7 and 100. Once a recurrence matches the program on many sizes, solving it is pure mathematics.
Example 2: maximum by halves
Finding the maximum of values recursively: split in two halves, find each half's maximum, return the larger. Counting comparisons:
Here , and . Unrolling suggests , the same as a simple loop, and an induction confirms it: . Divide and conquer does not always save work; here it only reorganizes it (which helps for parallel hardware, where the two halves can run at the same time).
Example 3: several recurrences, checked by counting
The program below has four recursive procedures. Each one returns how many units of the measured cost it used, so the program itself produces the exact value of its recurrence.
tri_sumsplits into three parts of size about and adds the three results after a linear scan: .karatsubamultiplies two -digit numbers with three recursive products of half-size numbers, counting one-digit multiplications: , for a power of 2.pick_min_sort(selection sort written recursively) puts the minimum first by a scan of comparisons and recurses on the remaining items: , .merge_sortcounts the elements written by merges: , .
def tri_sum(xs): # returns (sum, cost): cost = elements scanned
n = len(xs)
if n <= 2:
return sum(xs), n
k = n // 3
parts = [xs[:k], xs[k:2 * k], xs[2 * k:]]
total, cost = 0, n # the split scans all n elements once
for p in parts:
s, c = tri_sum(p)
total, cost = total + s, cost + c
return total, cost
def karatsuba(x, y, n): # n-digit numbers, n a power of 2; returns (x*y, digit mults)
if n == 1:
return x * y, 1
h = n // 2
x1, x0 = divmod(x, 10 ** h)
y1, y0 = divmod(y, 10 ** h)
hi, c1 = karatsuba(x1, y1, h)
lo, c2 = karatsuba(x0, y0, h)
# (x1 + x0)(y1 + y0) may carry into an extra digit; take its last h digits
# and fix the carry with additions and shifts only, so it still costs one product
s, t = x1 + x0, y1 + y0
sh, sl = divmod(s, 10 ** h)
th, tl = divmod(t, 10 ** h)
mid, c3 = karatsuba(sl, tl, h)
mid += (sh * tl + th * sl) * 10 ** h + sh * th * 10 ** (2 * h) # sh, th are 0 or 1
return hi * 10 ** (2 * h) + (mid - hi - lo) * 10 ** h + lo, c1 + c2 + c3
def pick_min_sort(xs): # returns (sorted list, comparisons)
if len(xs) <= 1:
return list(xs), 0
m = 0
for i in range(1, len(xs)):
if xs[i] < xs[m]:
m = i
rest, c = pick_min_sort(xs[:m] + xs[m + 1:])
return [xs[m]] + rest, c + len(xs) - 1
def merge_sort(xs): # returns (sorted list, elements written by merges)
if len(xs) <= 1:
return list(xs), 0
h = (len(xs) + 1) // 2
l, c1 = merge_sort(xs[:h])
r, c2 = merge_sort(xs[h:])
return sorted(l + r), c1 + c2 + len(xs) # sorted() stands in for the merge
from functools import lru_cache
T = lru_cache(None)(lambda n: n if n <= 2 else n + 2 * T(n // 3) + T(n - 2 * (n // 3)))
M = lru_cache(None)(lambda n: 1 if n == 1 else 3 * M(n // 2))
S = lru_cache(None)(lambda n: 0 if n <= 1 else S(n - 1) + n - 1)
W = lru_cache(None)(lambda n: 0 if n <= 1 else W((n + 1) // 2) + W(n // 2) + n)
print("procedure n measured recurrence")
for n in [9, 27, 30]:
print(f"tri_sum {n:4} {tri_sum(list(range(n)))[1]:8} {T(n):10}")
for n in [8, 16, 32]:
x, y = int("9" * n), int("8" * n)
prod, c = karatsuba(x, y, n)
assert prod == x * y
print(f"karatsuba {n:4} {c:8} {M(n):10}")
for n in [10, 50]:
print(f"pick_min {n:4} {pick_min_sort(list(range(n, 0, -1)))[1]:8} {S(n):10}")
for n in [10, 1000]:
print(f"merge_sort {n:4} {merge_sort(list(range(n)))[1]:8} {W(n):10}")procedure n measured recurrence
tri_sum 9 27 27
tri_sum 27 108 108
tri_sum 30 120 120
karatsuba 8 27 27
karatsuba 16 81 81
karatsuba 32 243 243
pick_min 10 45 45
pick_min 50 1225 1225
merge_sort 10 34 34
merge_sort 1000 9976 9976
Each recurrence was written by looking only at the shape of the procedure, and each one predicts the measured count exactly. Notice how tri_sum had to handle sizes that are not multiples of 3: its parts have sizes , and , and the exact recurrence says so. For powers of 3 it simplifies to , so .
Karatsuba's three products instead of four give , about , which is less than the one-digit products of school multiplication. pick_min_sort is recursive but not divide and conquer: it shrinks the input by one, not by a factor, and is quadratic. A recurrence of the form is a warning sign of that.
Floors, ceilings and base cases rarely matter
Real programs split into and ; textbooks write . That is safe for the recurrences in this course: replacing by its floor or ceiling, or adding a constant to the argument, changes the solution by at most a constant factor. Likewise the base case: whether the recursion stops at or , and whether the base cost is 1 or 50, only changes constant factors as long as the base case is a constant-size problem with constant cost. The program compares the exact merge-sort count with floors and ceilings against for sizes that are not powers of 2.
import math
from functools import lru_cache
@lru_cache(None)
def W(n): # exact: ceil and floor halves
return 0 if n <= 1 else W((n + 1) // 2) + W(n // 2) + n
for n in [1000, 1023, 1025, 5000, 99999, 10**6 + 1]:
print(f"n = {n:7} W(n) / (n lg n) = {W(n) / (n * math.log2(n)):.4f}")n = 1000 W(n) / (n lg n) = 1.0010
n = 1023 W(n) / (n lg n) = 1.0000
n = 1025 W(n) / (n lg n) = 1.0001
n = 5000 W(n) / (n lg n) = 1.0060
n = 99999 W(n) / (n lg n) = 1.0048
n = 1000001 W(n) / (n lg n) = 1.0010
The ratio stays within about half a percent of 1 whatever the rounding does, so for all , not only for powers of 2. The usual habit, which this course follows, is to solve the clean recurrence for exact powers of and to note that floors and ceilings do not change the order of growth. A proof for all is possible but rarely enlightening; When the Master Theorem Fails names the theorem (Akra-Bazzi) that settles it in general.
Common mistake: counting the work of the recursive calls twice. The term is only the work done in this call outside its recursive calls. A merge that touches elements contributes once; the elements it touches inside the children are already counted by .
Test yourself
A procedure on input size makes four recursive calls, each on size , and does other work. Which recurrence describes it?
Binary search makes at most probes, . What is ?
- 6
- 7
- 50
- 100
Which recurrence signals an algorithm that is recursive but not divide and conquer?
Replacing by in merge sort's recurrence changes the solution by
- at most a constant factor
- a factor of
- a factor of
- nothing for any