Recursion and Dynamic Programming
Factorial (Recursive)
factorial(0) = 1, otherwise factorial(n) = n * factorial(n - 1). The
smallest example of recursion with a single base case.
Algorithm
Basic Implementation
basic.cpp
#include <iostream>
int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int result = factorial(5);
std::cout << result << std::endl;
return 0;
}
Complexity
- Time: O(n)
- Space: O(n) call stack
Implementation notes
- In C++, the function is
int factorial(int n), so each recursive call receives its own copiedintparameter and returns anintresult. - The only base case in the checked source is
if (n == 0) return 1;; there is no guard for negative inputs. return n * factorial(n - 1);builds normal stack frames forf(5),f(4),f(3),f(2),f(1), andf(0)before the base case returns.- The trace shows the unwind values exactly:
1 * 1 = 1,2 * 1 = 2,3 * 2 = 6,4 * 6 = 24, and5 * 24 = 120. mainstoresfactorial(5)inint resultand prints it withstd::cout << result << std::endl, producing120.- Visible memory use is the call-stack frames only; there are no pointer or
reference parameters and no heap container mutation. Larger inputs can exceed
the range of C++
int, and this source does not add overflow handling.
base case
`if (n == 0) return 1;`
recursive call
`return n * factorial(n - 1);`