Recursion and divide and conquer
Recursion hands a problem to a smaller copy of itself: say when to stop, how it shrinks and how to combine, so n Hanoi discs take 2ⁿ − 1 moves; divide and conquer splits 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 <iostream>2using namespace std;3 4long long moves = 0;5 6void hanoi(int n, char from, char via, char to) {7 if (n == 1) { // base case: move one disc directly8 moves++;9 cout << from << " → " << to << '\n';10 return;11 }12 hanoi(n - 1, from, to, via); // the top n - 1 to the spare peg first13 moves++; // the biggest one14 cout << from << " → " << to << '\n';15 hanoi(n - 1, via, from, to); // then the n - 1 back on top16}17 18unsigned long long T(int n) { // count the moves only: T(n) = 2T(n - 1) + 119 if (n == 1) return 1;20 return 2 * T(n - 1) + 1;21}22 23int main() {24 hanoi(3, 'A', 'B', 'C');25 cout << "3 discs: " << moves << " moves\n";26 cout << "20 discs: " << T(20) << " moves\n";27 cout << "64 discs: " << T(64) << " moves\n";28 return 0;29}
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. 2⁶⁴ − 1 is exactly the largest number an unsigned long long holds; one more disc and it overflows.
How many moves for 10 discs?
1#include <iostream>2using namespace std;3 4long long moves = 0;5 6void hanoi(int n, char from, char via, char to) {7 if (n == 1) {8 moves++;9 return;10 }11 hanoi(n - 1, from, to, via);12 moves++;13 hanoi(n - 1, via, from, to);14}15 16int main() {17 hanoi(10, 'A', 'B', 'C');18 cout << moves << '\n';19 return 0;20}
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.
cout << from << " → " << to << '\n';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 <iostream>2using namespace std;3 4long long power(long long x, int n) {5 if (n == 0) return 1;6 long long h = power(x, );7 h = h * h;8 if (n % 2 == 1) h = h * x;9 return h;10}11 12int main() {13 cout << power(2, 10) << " " << power(3, 7) << "\n";14 return 0;15}
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 <iostream>2#include <vector>3using namespace std;4 5int max_of(const vector<int>& a, int lo, int hi) {6 // base case: lo == hi; otherwise mid = (lo + hi) / 2, recurse on both sides, return the bigger7 return a[lo];8}9 10int main() {11 vector<int> a = {3, 9, 2, 7, 5, 8, 1};12 vector<int> b = {-4, -8, -3, -6};13 cout << max_of(a, 0, 6) << ' ' << max_of(b, 0, 3) << '\n';14 return 0;15}
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 <iostream>2using namespace std;3 4const long long MOD = 1000000007;5long long calls;6 7long long power(long long x, int n) {8 calls++;9 if (n == 0) return 1; // base case10 long long h = power(x, n / 2); // worked out once11 h = h * h % MOD; // combine: square it12 if (n % 2 == 1) h = h * x % MOD; // odd: one more x13 return h;14}15 16long long power_bad(long long x, int n) {17 calls++;18 if (n == 0) return 1;19 long long h = power_bad(x, n / 2) * power_bad(x, n / 2) % MOD; // worked out twice20 if (n % 2 == 1) h = h * x % MOD;21 return h;22}23 24int main() {25 for (int n : {10, 1000, 50000}) {26 calls = 0;27 long long a = power(3, n);28 long long good = calls;29 calls = 0;30 long long b = power_bad(3, n);31 cout << "n = " << n << ": result " << a << " / " << b32 << ", calls " << good << " vs " << calls << "\n";33 }34 return 0;35}
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 <iostream>2using namespace std;3 4long calls = 0;5 6long long power_bad(long long x, int n) {7 calls++;8 if (n == 0) return 1;9 long long h = power_bad(x, n / 2) * power_bad(x, n / 2);10 if (n % 2 == 1) h = h * x;11 return h;12}13 14int main() {15 power_bad(2, 8);16 cout << calls << "\n";17 return 0;18}
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 <iostream>2using namespace std;3 4long long power(long long x, int n, long long m) {5 // n == 0 returns 1; h = power(x, n / 2, m); h = h * h % m; if n is odd, times x6 return 1;7}8 9int main() {10 const long long M = 1000000007;11 cout << power(2, 10, M) << ' ' << power(2, 30, M) << ' ' << power(3, 100000, M) << '\n';12 return 0;13}
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(const vector<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)?
With the STL
Writing recursion and divide and conquer in C++, three things come up often:
- Recursive lambdas: a lambda can't call itself by name, so declare a
function<return type(parameters)>first and capture it, along with everything else, with[&]. The recursive function can then live insidemainand usemain's arrays directly, with no globals. std::pow(<cmath>): works indouble, not in whole numbers. Adoublehas 53 bits of precision, so whole numbers above 2⁵³ ≈ 9 × 10¹⁵ can't all be stored exactly, and it can't take a modulus either. For whole-number powers, or powers modulo m, write fast power yourself.accumulate(<numeric>): adds up a range, one line instead of a loop. The type of the starting value is the type it adds in:0adds inint,doubles need0.0, and a sum that may passintneeds0LL.
1#include <iostream>2#include <vector>3#include <functional>4#include <numeric>5#include <cmath>6using namespace std;7 8int main() {9 vector<int> a = {3, 9, 2, 7, 5, 8, 1};10 11 function<int(int, int)> max_of = [&](int lo, int hi) { // maximum by divide and conquer12 if (lo == hi) return a[lo];13 int mid = (lo + hi) / 2;14 return max(max_of(lo, mid), max_of(mid + 1, hi));15 };16 cout << "maximum: " << max_of(0, (int)a.size() - 1) << '\n';17 18 function<long long(long long, int)> power = [&](long long x, int n) -> long long {19 if (n == 0) return 1;20 long long h = power(x, n / 2);21 return n % 2 ? h * h * x : h * h;22 };23 cout << "std::pow 2^10: " << pow(2, 10) << '\n'; // small ones are fine24 cout << "fast power 2^53 + 1: " << power(2, 53) + 1 << '\n';25 cout << "std::pow 2^53 + 1: " << (long long)(pow(2, 53) + 1) << '\n'; // a double can't add this 126 27 cout << "accumulate sum: " << accumulate(a.begin(), a.end(), 0) << '\n';28 vector<double> half = {0.5, 0.5, 0.5};29 cout << "start 0.0: " << accumulate(half.begin(), half.end(), 0.0) << '\n';30 cout << "start 0: " << accumulate(half.begin(), half.end(), 0) << '\n'; // cut to int at every step31 return 0;32}
maximum: 9 std::pow 2^10: 1024 fast power 2^53 + 1: 9007199254740993 std::pow 2^53 + 1: 9007199254740992 accumulate sum: 35 start 0.0: 1.5 start 0: 0
2⁵³ = 9007199254740992, and up there neighbouring doubles are 2 apart, so pow(2, 53) + 1 can't be stored and falls back to 2⁵³; fast power in long long is exact. Bigger still (3³⁵, say), all pow can give is the double nearest the true value. With 0 as the start, accumulate adds in int: 0 + 0.5 is cut to 0, and three times over it's still 0.
What's inside: function<> is a box that holds anything callable, and each call goes through one more step, a little slower than a plain function; where time is tight, write a plain function. Divide and conquer is all over the STL too: std::sort is quicksort (switching to heap sort when the recursion gets too deep, and insertion sort for the last short pieces), and stable_sort is merge sort.
| Code | What it does | Cost |
|---|---|---|
function<int(int, int)> f = [&](int a, int b) { … }; | A recursive lambda | One extra indirect jump per call compared to a plain function |
pow(x, n) | A power in double | O(1), but inexact above 2⁵³ and no modulus |
| Fast power by hand | Whole-number powers, powers modulo m | O(log n) multiplications |
accumulate(b, e, 0LL) | A sum, typed by the starting value | O(n) |
sort / stable_sort | Sorting by divide and conquer | O(n log n) |
In interviews: "implement pow(x, n)" is fast power; ask whether n can be negative (then work out x to the −n and take the reciprocal), and when n = INT_MIN, −n overflows, so turn it into a long long first. Asked for a recursion's time, draw the recursion tree and say "this many levels, this much on each"; asked for its space, give the recursion depth.
The two accumulate calls differ only in the starting value: 0 and 0.0. What does the program print?
1#include <iostream>2#include <vector>3#include <numeric>4using namespace std;5 6int main() {7 vector<double> v = {1.5, 2.5};8 cout << accumulate(v.begin(), v.end(), 0) << " "9 << accumulate(v.begin(), v.end(), 0.0) << "\n";10 return 0;11}
0 is an int: 0 + 1.5 = 1.5 is stored back as an int, 1; then 1 + 2.5 = 3.5 is cut to 3. 0.0 is a double: 1.5 + 2.5 = 4, exactly. So a sum of doubles starts at 0.0, and one that may outgrow an int starts at 0LL.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
- For whole-number powers write fast power, not std::pow, which returns a double
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}