Recursion and divide and conquer
Recursion hands a problem to a smaller copy of itself, with a base case, a smaller call and a way to combine the answers, so the Tower of Hanoi takes 2ⁿ − 1 moves; divide and conquer cuts a problem into independent parts, as fast power does in O(log n) multiplications.
The Tower of Hanoi with 64 discs, one move a second: how long does it take? 2⁶⁴ − 1 seconds, about 585 billion years. Nobody counted that one by one; it follows from a single sentence: "to move n discs, move the top n − 1 out of the way, move the biggest, then move the n − 1 back on top." That sentence is a recursion. The algorithm design ideas of this chapter (divide and conquer, backtracking, dynamic programming) all start here.
The three parts of a recursion
A recursive function has to make three things clear:
- The base case: how small the problem must be to answer straight away, with no further call;
- Smaller: hand the problem to a smaller copy of yourself;
- Combine: take the smaller problem's answer and work out your own.
The Tower of Hanoi: move n discs from A to C, using B on the way, never putting a big disc on a small one.
- Base case: just 1 disc, move it from A to C;
- Smaller: first move the top n − 1 from A to B (using C): a Tower of Hanoi of size n − 1;
- Combine: move the biggest A → C, then move the n − 1 on B to C (using A).
Draw each call as a node, and the two smaller problems it calls as its children: that's the recursion tree. In the figure, the arrows down are calls, and the dashed arrows up are returns.
1#include <stdio.h>2 3long moves = 0;4 5void hanoi(int n, char from, char via, char to) {6 if (n == 1) { // base case: one disc, just move it7 moves++;8 printf("%c → %c\n", from, to);9 return;10 }11 hanoi(n - 1, from, to, via); // the top n - 1 out of the way first12 moves++; // the biggest one13 printf("%c → %c\n", from, to);14 hanoi(n - 1, via, from, to); // then the n - 1 back on top15}16 17unsigned long long T(int n) { // only counting: T(n) = 2T(n - 1) + 118 if (n == 1) return 1;19 return 2 * T(n - 1) + 1;20}21 22int main(void) {23 hanoi(3, 'A', 'B', 'C');24 printf("3 discs: %ld moves\n", moves);25 printf("20 discs: %llu moves\n", T(20));26 printf("64 discs: %llu moves\n", T(64));27 return 0;28}
A → C A → B C → B A → C B → A B → C A → C 3 discs: 7 moves 20 discs: 1048575 moves 64 discs: 18446744073709551615 moves
Why 2ⁿ − 1: let T(n) be the moves for n discs; T(1) = 1 and T(n) = 2T(n − 1) + 1. Each level down the recursion tree has twice as many nodes: 1 + 2 + 4 + … + 2ⁿ⁻¹ = 2ⁿ − 1. One more disc doubles the moves, plus one.
How many moves for 10 discs?
1#include <stdio.h>2 3long moves = 0;4 5void hanoi(int n, char from, char via, char to) {6 if (n == 1) {7 moves++;8 return;9 }10 hanoi(n - 1, from, to, via);11 moves++;12 hanoi(n - 1, via, from, to);13}14 15int main(void) {16 hanoi(10, 'A', 'B', 'C');17 printf("%ld\n", moves);18 return 0;19}
hanoi(3, A → C) takes 7 moves. What is move 4?
A recursive function has no way out (or its way out can never be reached). What happens when it runs?
Put the 3 lines after Hanoi's way out in order, so the program for 2 discs prints the right 3 moves.
printf("%c → %c\n", from, to);hanoi(n - 1, from, to, via);hanoi(n - 1, via, from, to);
A → B A → C B → C
Divide and conquer: cut, solve each, combine
Divide and conquer is one way to use recursion: cut the problem into several problems of the same kind that don't depend on each other, solve each recursively, then combine the answers. Chapter 7's merge sort is exactly this:
| Merge sort | Fast power | |
|---|---|---|
| Cut | Split in the middle | xⁿ becomes x^(n/2) |
| Solve each | Sort both halves recursively | Work out x^(n/2) recursively |
| Combine | Merge two sorted halves, O(n) | Square it, and times one more x if n is odd |
| Base case | A single number | n = 0, the answer is 1 |
Fast power: working out xⁿ the plain way takes n − 1 multiplications. But x¹³ = (x⁶)² × x, x⁶ = (x³)², x³ = (x¹)² × x: n halves each time, so there are only log₂ n levels.
1long long power(long long x, int n) {2 calls++;3 if (n == 0) return 1; // base case4 long long h = power(x, n / 2); // worked out once5 h = h * h % MOD; // combine: square it6 if (n % 2 == 1) h = h * x % MOD; // odd: one more x7 return h;8}
Fast power: fill in the argument of the recursive call so the program prints 1024 2187.
1#include <stdio.h>2 3long long power(long long x, int n) {4 if (n == 0) return 1;5 long long h = power(x, );6 h = h * h;7 if (n % 2 == 1) h = h * x;8 return h;9}10 11int main(void) {12 printf("%lld %lld\n", power(2, 10), power(3, 7));13 return 0;14}
n - 1 it shrinks by just 1 each time, and h * h no longer gives the right answer either.A maximum by divide and conquer
✓Find the maximum of a[lo..hi] by divide and conquer: a single number is its own maximum; otherwise split in the middle, find each half's maximum, and return the bigger.
9 -3
1#include <stdio.h>2 3int max_of(int a[], int lo, int hi) {4 // base case: lo == hi; otherwise mid = (lo + hi) / 2, recurse on both halves, return the bigger5 return a[lo];6}7 8int main(void) {9 int a[] = {3, 9, 2, 7, 5, 8, 1};10 int b[] = {-4, -8, -3, -6};11 printf("%d %d\n", max_of(a, 0, 6), max_of(b, 0, 3));12 return 0;13}
Don't solve the same subproblem twice
Fast power is fast because power(x, n / 2) is worked out once, kept in h, and multiplied by itself. Write it twice in the same expression and the result is the same, but the cost is completely different. This step's program puts the right power next to the wrong power_bad (which writes power(x, n / 2) twice) and compares how many calls each makes. The results soon overflow long long, so both are taken modulo 1000000007 (the usual way in exams and interviews).
1#include <stdio.h>2 3#define MOD 10000000074long calls;5 6long long power(long long x, int n) {7 calls++;8 if (n == 0) return 1; // base case9 long long h = power(x, n / 2); // worked out once10 h = h * h % MOD; // combine: square it11 if (n % 2 == 1) h = h * x % MOD; // odd: one more x12 return h;13}14 15long long power_bad(long long x, int n) {16 calls++;17 if (n == 0) return 1;18 long long h = power_bad(x, n / 2) * power_bad(x, n / 2) % MOD; // worked out twice19 if (n % 2 == 1) h = h * x % MOD;20 return h;21}22 23int main(void) {24 int ns[] = {10, 1000, 50000};25 for (int i = 0; i < 3; i++) {26 calls = 0;27 long long a = power(3, ns[i]);28 long good = calls;29 calls = 0;30 long long b = power_bad(3, ns[i]);31 printf("n = %-5d result %lld / %lld calls: %ld vs %ld\n", ns[i], a, b, good, calls);32 }33 return 0;34}
n = 10 result 59049 / 59049 calls: 5 vs 31 n = 1000 result 56888193 / 56888193 calls: 11 vs 2047 n = 50000 result 878110356 / 878110356 calls: 17 vs 131071
Same results, wildly different numbers of calls. At n = 50000 the right version makes 17 calls and the wrong one over 130,000, slower than multiplying 50,000 times the plain way. The only difference is one line: the same smaller problem worked out twice.
How many times is power_bad called in all for power_bad(2, 8)?
1#include <stdio.h>2 3long calls = 0;4 5long long power_bad(long long x, int n) {6 calls++;7 if (n == 0) return 1;8 long long h = power_bad(x, n / 2) * power_bad(x, n / 2);9 if (n % 2 == 1) h = h * x;10 return h;11}12 13int main(void) {14 power_bad(2, 8);15 printf("%ld\n", calls);16 return 0;17}
How do you fix power_bad?
n - 1 would make it O(n) levels instead.Fast power modulo m
✓Complete power(x, n, m) to work out xⁿ % m, calling itself only once.
1024 73741817 916902199
1#include <stdio.h>2 3long long power(long long x, int n, long long m) {4 // n == 0 returns 1; h = power(x, n / 2, m); h = h * h % m; one more x if n is odd5 return 1;6}7 8int main(void) {9 printf("%lld %lld %lld\n", power(2, 10, 1000000007), power(2, 30, 1000000007), power(3, 100000, 1000000007));10 return 0;11}
The cost: levels × work per level
You can estimate a recursion's cost straight from its tree: how many levels, how much work on each level in all, multiplied (added up when the levels differ). That's the idea behind the "master theorem", and it gets the common cases right with no formula to learn:
| Recurrence | Example | Levels | Work per level | In all |
|---|---|---|---|---|
| T(n) = T(n/2) + 1 | Binary search, fast power | log n | 1 | O(log n) |
| T(n) = 2T(n/2) + n | Merge sort | log n | n (all the pieces on a level add up to n numbers) | O(n log n) |
| T(n) = 2T(n/2) + 1 | power_bad, an array's maximum by divide and conquer | log n | 1, 2, 4… n on the last | O(n) |
| T(n) = 2T(n − 1) + 1 | Tower of Hanoi | n | 1, 2, 4… 2ⁿ⁻¹ | O(2ⁿ) |
| T(n) = T(n − 1) + n | Recursive selection sort | n | n, n − 1, … | O(n²) |
Looking at a recursion, ask two things first: how many smaller problems each call makes (how wide the tree is), and how much smaller they get (how deep: halving is log n levels, minus one is n levels). Halving or minus one is the difference between log n and n; working the same smaller problem out once or twice is the difference between log n and n, or even n and 2ⁿ.
Recursion has one more cost: each level of calls takes a stack frame. A depth of log n is fine; a depth of n (walking a linked list of a million nodes recursively, say) can overflow the stack, and then it should become a loop.
main()power(3, 13)power(3, 13)n = 13power(3, 6)n = 6power(3, 3)n = 3power(3, 1)n = 1power(3, 0)n = 0In exams: "how many moves for n discs in the Tower of Hanoi" (2ⁿ − 1); "write the recurrence and give the time complexity", like T(n) = 2T(n/2) + n giving O(n log n); "which structure does recursion use" (a stack); "the space complexity of a recursive algorithm" depends on the deepest the recursion goes, not on the total number of calls.
What is the time complexity of summing an array by divide and conquer?
1int sum(int a[], int lo, int hi) {2 if (lo == hi) return a[lo];3 int mid = (lo + hi) / 2;4 return sum(a, lo, mid) + sum(a, mid + 1, hi);5}
hanoi(n) makes 2ⁿ − 1 calls in all. What is its space complexity (the deepest the call stack gets)?
Summary
Recursion and divide and conquer
- Three parts: a base case, hand it to a smaller self, combine the answers
- Tower of Hanoi: T(n) = 2T(n − 1) + 1, 2ⁿ − 1 moves
- Divide and conquer: cut into independent parts, solve each, combine (merge sort, fast power)
- Cost = the recursion tree's levels × the work per level; never work the same part out twice
1long long power(long long x, int n) {2 if (n == 0) return 1;3 long long h = power(x, n / 2);4 return n % 2 ? h * h * x : h * h;5}