- Base case — the stopping condition. Without it the function calls itself forever and crashes.
- Recursive case — the step that calls the function again with a strictly smaller input, moving toward the base case.
Factorial
The factorial ofn (written n!) is the product of all integers from 1 to n. It is defined recursively as:
0! = 1and1! = 1(base cases)n! = n × (n-1)!(recursive case)
if/else. Both encode the same logic: if n is 0 or 1 return 1 immediately, otherwise multiply n by the factorial of n-1.
Fibonacci
The Fibonacci sequence starts1, 1, 2, 3, 5, 8, …. Each number is the sum of the two before it:
fibonacci(1) = 1andfibonacci(2) = 1(base cases)fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)(recursive case)
fibonacci makes two recursive calls per invocation, unlike factorial which makes only one. That difference has a significant impact on performance (see Time complexity below).
The call stack
When you call a recursive function, each invocation is pushed onto the call stack and waits until the call it made returns. Here is the full trace forfactorial(4):
n and a pointer back to the caller.
Time complexity
| Function | Calls per invocation | Total calls for input n | Time complexity |
|---|---|---|---|
factorial(n) | 1 | n | O(n) |
fibonacci(n) | 2 | ~2ⁿ | O(2ⁿ) |
factorial is linear because each step reduces n by exactly 1. fibonacci is exponential because each call branches into two, and many of those branches recompute the same subproblems. fibonacci(5) computes fibonacci(3) twice, fibonacci(2) three times, and so on.
The exponential cost of naive recursive Fibonacci can be eliminated with memoization (caching results) or by rewriting the function iteratively. The implementation in this project is intentionally simple to illustrate the recursion concept.