6 / 7 · Basic
Recursion
Moving a Tower of Hanoi of 64 disks takes 18,446,744,073,709,551,615 moves; a recursive function describes the solution in four lines.
Jump to the 11 practice questionsYou will learn
- Write a function that calls itself, with a base case
- Follow the call stack as calls wait and return
- Solve the Tower of Hanoi recursively
Before this: How fast? Big O notation
1Explain
A function that calls itself
Some problems contain a smaller copy of themselves. The factorial of 5, written 5!, is 5 × 4 × 3 × 2 × 1 = 120. Look at it again: it is 5 × (4 × 3 × 2 × 1), which is 5 × 4!. In general n! = n × (n − 1)!, so to compute a factorial you can compute a smaller factorial and multiply. A function that solves a problem by calling itself on a smaller version is recursive.
function factorial(n) {
if (n <= 1) return 1; // base case: stop here
return n * factorial(n - 1); // recursive case: a smaller problem
}
console.log(factorial(5)); // 1201202Explain
Two parts: base case and recursive case
Every recursive function needs two parts. The base case is an input small enough to answer directly, without another call: here, the factorial of 1 is 1. The recursive case reduces the problem and calls the function again. Each call must move closer to the base case. If it does not, for example if you wrote factorial(n + 1) by mistake, the calls never end.
3Problem
The base case
What does the base case do?
Hint
What would happen without it?
Solution
Answer: Answers a small input directly and stops the chain of calls
Without a base case the calls would never end.
4Explain
The call stack
How does the computer keep track of all those unfinished calls? When factorial(5) runs, it reaches 5 * factorial(4) and has to wait for the answer. The computer puts the waiting call on a stack, a pile where the last item placed is the first one taken off. factorial(4) waits for factorial(3), and so on down to factorial(1), which returns 1 straight away.
Each call gets its own box with its own n. The boxes pile up while each call waits for the one below, then they return one by one, last first.
function factorial(n) {if (n <= 1) return 1;const rest = factorial(n - 1);return n * rest;}console.log(factorial(4));
24
5Problem
Calls on the stack
While factorial(5) is computing factorial(1), how many factorial calls are on the stack, including that one?
Hint
Count factorial(5) down to factorial(1).
Solution
Answer: 5
factorial(5), (4), (3), (2) and (1) are all unfinished.
6Problem
Last in, first out
A stack takes items off in which order?
Hint
Which call finished first in the trace?
Solution
Answer: Last in, first out
The call that started last finishes first, which is how recursion unwinds.
7Problem
6!
What is 6! (6 factorial)?
Hint
6! = 6 × 5!, and 5! = 120.
Solution
Answer: 720
A factorial multiplies n by the factorial of the number just below it, so 6! = 6 × 5! = 6 × 120 = 720.
8Explain
When the stack runs out
The stack has a limited size. A recursion that never reaches its base case keeps adding calls until the space runs out, and JavaScript stops with an error; in Chrome and Node.js the message is "RangeError: Maximum call stack size exceeded". The same limit means that very deep recursion, hundreds of thousands of levels, is better written as a loop.
9Problem
No base case
What happens if a recursive function never reaches its base case?
Hint
Every waiting call takes stack space.
Solution
Answer: The call stack fills up and the program stops with an error
Each waiting call takes stack space. In Chrome and Node.js: RangeError: Maximum call stack size exceeded.
10Explain
The Tower of Hanoi
Thinking step by step about where each disk goes gets confusing quickly. Thinking recursively makes it short. To move n disks from A to C: first move the top n − 1 disks out of the way, from A to B. Then move the largest disk from A to C. Then move the n − 1 disks from B onto it at C.
Two disks, three moves: the small disk out of the way to B, the big disk to C, the small disk on top.
function hanoi(n, from, to, via) {if (n === 0) return;hanoi(n - 1, from, via, to);console.log("disk " + n + ": " + from + " -> " + to);hanoi(n - 1, via, to, from);}hanoi(2, "A", "C", "B");
disk 1: A -> B disk 2: A -> C disk 1: B -> C
11Problem
The first step
To move n disks from A to C, what is the first step of the recursive plan?
Hint
The largest disk can move only when nothing is on it.
Solution
Answer: Move the top n − 1 disks from A to B
The largest disk can only move when nothing is on top of it and C is empty.
12Explore
Counting the moves
How many moves does n disks take? Moving n disks costs two moves of n − 1 disks plus one: M(n) = 2M(n − 1) + 1, with M(1) = 1. That gives 1, 3, 7, 15, 31, so M(n) = 2ⁿ − 1, and no solution can use fewer. Ten disks take 1,023 moves. Sixty-four disks take 2⁶⁴ − 1 = 18,446,744,073,709,551,615 moves; at one move per second that is about 585 billion years.
Each extra disk doubles the count and adds one: 2ⁿ − 1.
function moves(n) {
if (n === 0) return 0;
return 2 * moves(n - 1) + 1;
}
console.log(moves(1));113Problem
Four disks
How many moves does the Tower of Hanoi take with 4 disks?
Hint
2 × 7 + 1.
Solution
Answer: 15
Moving n disks takes twice the moves for n − 1 disks plus one, which gives 2ⁿ − 1: 2⁴ − 1 = 15, or 2 × 7 + 1.
14Explore
Repeated work
Anything written with recursion can be written with a loop and a stack of your own, and simple cases such as factorial are often clearer as loops. Recursion shines when the problem itself is shaped like a tree: splitting a list in merge sort, exploring folders inside folders, or searching a maze, which is the topic of the last unit.
The value grows slowly, but the number of calls explodes, because the same smaller values are worked out again and again.
let calls = 0;
function fib(n) {
calls++;
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(5));
console.log(calls); // how many calls5
1515Problem
Why fib is slow
Why is the plain recursive fib slow?
Hint
Count how often fib(8) is computed inside fib(10).
Solution
Answer: It computes the same smaller values many times
fib(8) is computed twice inside fib(10), fib(7) three times, and so on.
16Practice
Recursive factorial
Write factorial recursively. It should print 120 and 3628800.
120
3628800function factorial(n) {
// Base case for n <= 1, then n * factorial(n - 1)
}
console.log(factorial(5));
console.log(factorial(10));
Hint
The base case must return 1: multiplying by 0 would wipe out every result.
A solution
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5));
console.log(factorial(10));17Practice
Count Hanoi moves
Write the recursive move count for the Tower of Hanoi. It should print 7 and 1023.
7
1023function moves(n) {
// Moves needed for n disks: 0 for no disks,
// otherwise twice moves(n - 1), plus 1.
}
console.log(moves(3));
console.log(moves(10));
Hint
Two moves of n − 1 disks, plus one move of the largest disk.
A solution
function moves(n) {
if (n === 0) return 0;
return 2 * moves(n - 1) + 1;
}
console.log(moves(3));
console.log(moves(10));18Explain
Common mistakes
function countdown(n) {
if (n === 0) return "go";
return countdown(n - 2);
}
console.log(countdown(3));RangeError: Maximum call stack size exceeded (line 2)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
Counting down by 2 from 3 jumps over 0, so the base case is never reached and the calls pile up until the stack is full. Test n <= 0 instead.
function sum(n) {
if (n === 0) return 0;
sum(n - 1) + n;
}
console.log(sum(4));undefinedfunction sum(n) {
if (n === 0) return 0;
return sum(n - 1) + n;
}
console.log(sum(4));10The recursive result must be returned. Without return the call works it out and throws it away, and the function gives undefined.
19
Summary
- A recursive function calls itself on a smaller version of the problem.
- It needs a base case that stops the calls.
- Waiting calls sit on the call stack, last in, first out.
- Tower of Hanoi: 2ⁿ − 1 moves; 64 disks would take about 585 billion years at one move per second.
- Watch for repeated work, as in plain recursive Fibonacci.