TExcelTAD
Home › Foundations of Algorithm Analysis › Writing Recurrences

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 T(n)T(n) in terms of TT 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 nn, and sort its work into three piles.

  1. Recursive calls. How many are there, and on inputs of what size? If there are aa calls, each on size about n/bn/b, they contribute a T(n/b)a\,T(n/b).
  2. Everything else. The work done in this call outside the recursive calls: splitting the input, combining results, loops, copying. Call it f(n)f(n).
  3. 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

T(n)={Θ(1)if n≤n0,a T(n/b)+f(n)if n>n0.T(n) = \begin{cases} \Theta(1) & \text{if } n \le n_0, \\ a\,T(n/b) + f(n) & \text{if } n > n_0. \end{cases}

Two warnings. First, aa and bb are separate numbers: aa counts calls, bb says how fast the size shrinks, and nothing forces a=ba = b. Second, TT 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 a[lo:hi]a[lo:hi] of a sorted array:

text
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 m=hi−lom = hi - lo elements, the left range a[lo:mid]a[lo:mid] has ⌊m/2⌋\lfloor m/2 \rfloor elements and the right range a[mid+1:hi]a[mid + 1:hi] has ⌈m/2⌉−1\lceil m/2 \rceil - 1, 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

P(n)=P(⌊n/2⌋)+1,P(0)=0.P(n) = P(\lfloor n/2 \rfloor) + 1, \qquad P(0) = 0.

Its solution is P(n)=⌊lg⁡n⌋+1P(n) = \lfloor \lg n \rfloor + 1 for n≥1n \ge 1. 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.

python · try it yourself
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 nn, gives ⌊lg⁡n⌋+1\lfloor \lg n \rfloor + 1 without floating point:

cpp · try it yourself
#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 nn values recursively: split in two halves, find each half's maximum, return the larger. Counting comparisons:

C(n)=C(⌈n/2⌉)+C(⌊n/2⌋)+1,C(1)=0.C(n) = C(\lceil n/2 \rceil) + C(\lfloor n/2 \rfloor) + 1, \qquad C(1) = 0.

Here a=2a = 2, b=2b = 2 and f(n)=1f(n) = 1. Unrolling suggests C(n)=n−1C(n) = n - 1, the same as a simple loop, and an induction confirms it: (⌈n/2⌉−1)+(⌊n/2⌋−1)+1=n−1(\lceil n/2 \rceil - 1) + (\lfloor n/2 \rfloor - 1) + 1 = n - 1. 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_sum splits into three parts of size about n/3n/3 and adds the three results after a linear scan: T(n)=3T(n/3)+nT(n) = 3T(n/3) + n.
  • karatsuba multiplies two nn-digit numbers with three recursive products of half-size numbers, counting one-digit multiplications: M(n)=3M(n/2)M(n) = 3M(n/2), M(1)=1M(1) = 1 for nn a power of 2.
  • pick_min_sort (selection sort written recursively) puts the minimum first by a scan of n−1n - 1 comparisons and recurses on the remaining n−1n - 1 items: S(n)=S(n−1)+(n−1)S(n) = S(n - 1) + (n - 1), S(1)=0S(1) = 0.
  • merge_sort counts the elements written by merges: W(n)=W(⌈n/2⌉)+W(⌊n/2⌋)+nW(n) = W(\lceil n/2 \rceil) + W(\lfloor n/2 \rfloor) + n, W(1)=0W(1) = 0.
python · try it yourself
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 ⌊n/3⌋\lfloor n/3 \rfloor, ⌊n/3⌋\lfloor n/3 \rfloor and n−2⌊n/3⌋n - 2\lfloor n/3 \rfloor, and the exact recurrence says so. For powers of 3 it simplifies to T(n)=n(log⁡3n+1)T(n) = n(\log_3 n + 1), so T(27)=27⋅4=108T(27) = 27 \cdot 4 = 108.

Karatsuba's three products instead of four give M(n)=3lg⁡n=nlg⁡3M(n) = 3^{\lg n} = n^{\lg 3}, about n1.585n^{1.585}, which is less than the n2n^2 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 S(n)=n(n−1)/2S(n) = n(n - 1)/2 is quadratic. A recurrence of the form T(n−1)+f(n)T(n - 1) + f(n) is a warning sign of that.

Floors, ceilings and base cases rarely matter

Real programs split nn into ⌈n/2⌉\lceil n/2 \rceil and ⌊n/2⌋\lfloor n/2 \rfloor; textbooks write 2T(n/2)2T(n/2). That is safe for the recurrences in this course: replacing n/bn/b 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 n≤1n \le 1 or n≤16n \le 16, 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 nlg⁡nn \lg n for sizes that are not powers of 2.

python · try it yourself
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 W(n)=Θ(nlg⁡n)W(n) = \Theta(n \lg n) for all nn, not only for powers of 2. The usual habit, which this course follows, is to solve the clean recurrence for exact powers of bb and to note that floors and ceilings do not change the order of growth. A proof for all nn 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 f(n)f(n) is only the work done in this call outside its recursive calls. A merge that touches nn elements contributes nn once; the elements it touches inside the children are already counted by T(n/2)T(n/2).

Test yourself

A procedure on input size nn makes four recursive calls, each on size n/2n/2, and does n2n^2 other work. Which recurrence describes it?

  1. T(n)=2T(n/4)+n2T(n) = 2T(n/4) + n^2
  2. T(n)=4T(n/2)+n2T(n) = 4T(n/2) + n^2
  3. T(n)=4T(n/4)+n2T(n) = 4T(n/4) + n^2
  4. T(n)=T(n/2)+4n2T(n) = T(n/2) + 4n^2

Binary search makes at most P(n)=P(⌊n/2⌋)+1P(n) = P(\lfloor n/2 \rfloor) + 1 probes, P(0)=0P(0) = 0. What is P(100)P(100)?

  1. 6
  2. 7
  3. 50
  4. 100

Which recurrence signals an algorithm that is recursive but not divide and conquer?

  1. T(n)=2T(n/2)+1T(n) = 2T(n/2) + 1
  2. T(n)=3T(n/3)+nT(n) = 3T(n/3) + n
  3. T(n)=T(n−1)+nT(n) = T(n - 1) + n
  4. T(n)=7T(n/2)+n2T(n) = 7T(n/2) + n^2

Replacing T(⌈n/2⌉)+T(⌊n/2⌋)T(\lceil n/2 \rceil) + T(\lfloor n/2 \rfloor) by 2T(n/2)2T(n/2) in merge sort's recurrence changes the solution by

  1. at most a constant factor
  2. a factor of lg⁡n\lg n
  3. a factor of nn
  4. nothing for any nn