Skip to content
  • Open the math solver
  • Ask the AI tutor
  • Find an AP course
  • Create a quiz
  • Open the calculator
  • Graphing Calculator
  • Browse all calculators
  • Read math guides
↑ ↓Enter to open · Esc to close
Solve a problem
AlgorithmsAlgorithmsCollege

Recursion

Base cases, recursive cases and recurrence relations.

A recursive function solves a problem by calling itself on a smaller version of the same problem. Every recursive function needs a base case that is answered directly and a recursive case that moves toward it. Factorial is the classic example: n!=n×(n−1)!n! = n \times (n - 1)!, with 0!=10! = 1 as the base case.

Recursion fits problems with self-similar structure, such as trees, nested folders, divide-and-conquer sorts and many puzzles. Each call waits on the call stack until the smaller call returns, so very deep recursion can overflow the stack, and naive recursion can repeat work, which memoisation fixes.

Key ideas

  • Always define the base case first and make sure every call moves toward it.
  • Trace with a call tree to see the order of calls and returns.
  • Recurrences describe cost: T(n)=T(n−1)+O(1)T(n) = T(n - 1) + O(1) gives O(n)O(n); T(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n) gives O(nlog⁡n)O(n \log n).
  • Naive Fibonacci is exponential; memoised Fibonacci is linear.

Worked example

Trace `f(n) = n == 0 ? 0 : n + f(n - 1)` for `f(4)`.

  1. f(4)=4+f(3)f(4) = 4 + f(3).
  2. f(3)=3+f(2)f(3) = 3 + f(2), f(2)=2+f(1)f(2) = 2 + f(1), f(1)=1+f(0)f(1) = 1 + f(0).
  3. Base case: f(0)=0f(0) = 0.
  4. Unwind: f(1)=1f(1) = 1, f(2)=3f(2) = 3, f(3)=6f(3) = 6, f(4)=10f(4) = 10.

Answer: 1010

Common mistakes

  • Missing or unreachable base case, causing infinite recursion.
  • Recursive calls that do not shrink the problem.
  • Ignoring repeated work in tree-shaped recursion.

Practice questions

Try each one, then open the answer. Numerical answers on this page are verified by an automated calculation check.

  1. 1.Compute 5!5! recursively.

    Show answer

    120120

  2. 2.Fibonacci with F(0)=0F(0) = 0, F(1)=1F(1) = 1: find F(10)F(10).

    Show answer

    5555

  3. 3.How many moves does Tower of Hanoi need for 5 discs (2n−12^n - 1)?

    Show answer

    3131

More in Algorithms