edubun
English
1 / 19

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 questions

You 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)); // 120
Output
120

2Explain

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.

  1. function factorial(n) {
  2. if (n <= 1) return 1;
  3. const rest = factorial(n - 1);
  4. return n * rest;
  5. }
  6. console.log(factorial(4));
Variables
Output
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.

  1. function hanoi(n, from, to, via) {
  2. if (n === 0) return;
  3. hanoi(n - 1, from, via, to);
  4. console.log("disk " + n + ": " + from + " -> " + to);
  5. hanoi(n - 1, via, to, from);
  6. }
  7. hanoi(2, "A", "C", "B");
Variables
Output
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));
Output
1

13Problem

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.

n
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 calls
Output
5
15

15Problem

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.

Expected output
120
3628800
Your code
function 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.

Expected output
7
1023
Your code
function 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));
Error message
RangeError: Maximum call stack size exceeded (line 2)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. 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.

Mistake
function sum(n) {
  if (n === 0) return 0;
  sum(n - 1) + n;
}
console.log(sum(4));
Output
undefined
Fixed
function sum(n) {
  if (n === 0) return 0;
  return sum(n - 1) + n;
}
console.log(sum(4));
Output
10

The 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.

Next unitGraph search: BFS and DFS
Full text · The whole lesson as one text

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)); // 120

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.

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. Then the stack unwinds: factorial(2) returns 2, factorial(3) returns 6, factorial(4) returns 24, and factorial(5) returns 120.

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.

The Tower of Hanoi

The Tower of Hanoi is a puzzle published by the French mathematician Édouard Lucas in 1883. There are three pegs and a stack of disks of different sizes on the first peg, largest at the bottom. The goal is to move the whole stack to the third peg. You may move only one disk at a time, only the top disk of a peg, and never put a larger disk on a smaller one.

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. Moving n − 1 disks is the same puzzle, one size smaller, and moving one disk is the base case. For 3 disks this gives 7 moves; the lab shows the stack of waiting calls at every move.

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(3, "A", "C", "B");  // 7 moves
Three disks, seven moves. The call stack on the right lists the hanoi calls that are waiting for this move to finish. Try 4 and 5 disks.

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. This is the O(2ⁿ) growth from the last unit.

Recursion, loops and 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. One trap is repeated work. The Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, … follow fib(n) = fib(n − 1) + fib(n − 2). Written directly as recursion, fib(10) = 55 makes 177 calls, fib(20) makes 21,891, and fib(30) makes 2,692,537, because the same smaller values are computed again and again. Remembering answers already found, or building up from the bottom with a loop, removes that waste.

Key points
  • 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.

Practice questions from Recursion on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 1 Introduction, 3 Sorting, 9 Breadth-First Search, 10 Depth-First Search (ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes) and Fall 2011 lecture 13 BFS notes (ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (MIT Press)
  • with the CLRS-based Khan Academy algorithms unit by Thomas Cormen and Devin Balkcom of Dartmouth (khanacademy.org/computing/computer-science/algorithms: binary search, selection sort analysis, merge sort, quicksort overview and analysis)
  • MacTutor History of Mathematics, Al-Khwarizmi (mathshistory.st-andrews.ac.uk/Biographies/Al-Khwarizmi: word algorithm from the Latin title Algoritmi de numero Indorum)
  • D. E. Joyce, Euclid's Elements Book VII Propositions 1 and 2 (mathcs.clarku.edu/~djoyce/elements/bookVII)
  • Wolfram MathWorld, Merge Sort (mathworld.wolfram.com/MergeSort.html: proposed by John von Neumann in 1945, after Knuth 1998 p. 159)
  • Stanford CS "Tony Hoare: Quicksort" (cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/quicksort.html: devised while a student at Moscow State University for Russian-English machine translation with a tape dictionary, programmed in Algol 60 and published 1961; the year 1959 from the Wikipedia Quicksort article and its cited sources)
  • Bodleian Libraries, Ada Lovelace (blogs.bodleian.ox.ac.uk/adalovelace: 1843 paper, Note G Bernoulli numbers)
  • Fourmilab text of Menabrea's Sketch with Lovelace's notes (fourmilab.ch/babbage/sketch.html)
  • Seven Bridges of Konigsberg (Euler 1736) and Tower of Hanoi (Edouard Lucas, 1883) checked against the Wikipedia articles and their cited sources.

Checked: 2026-10-17