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.cs
using System;
class Program {
static int Factorial(int n) {
if (n == 0) {
return 1;
}
return n * Factorial(n - 1);
}
static void Main() {
int result = Factorial(5);
Console.WriteLine(result);
}
}
Complexity
- Time: O(n)
- Space: O(n) call stack
Implementation notes
- The checked-in method is
static int Factorial(int n), so every argument and return value is a copiedint. The base case is exactlyn == 0, returning the literal1. - Each recursive call uses a normal CLR call-stack frame; there is no heap allocation or container state in the recursive path, so GC is not part of the replayed behavior.
- The multiplication is plain
n * Factorial(n - 1)with nocheckedblock. For the fixtureFactorial(5), overflow is not visible; the trace focuses on frame descent and unwind values such as5 * 24 = 120.
base case
`if (n == 0) return 1;`
recursive call
`n * Factorial(n - 1)`