Recursive frames
Each descent owns its arguments. Each return supplies the missing operand in its caller. For the fixed-width snippets use 0 ≤ n ≤ 20.
| Base case | Known direct answer | 0! = 1 |
| Progress measure | Strictly decreases | n becomes n − 1 |
| Auxiliary space | Maximum live frames | Factorial uses O(n) call stack |
| Backtracking | Undo shared mutation | Restore the path before its sibling branch |
Python
def factorial(n):
if n == 0: return 1
return n * factorial(n-1)C++
long long factorial(int n) {
if (n == 0) return 1;
return n * factorial(n-1);
}Java
static long factorial(int n) {
if (n == 0) return 1L;
return n * factorial(n-1);
}