Overview
Factorial n! = n × (n-1) × ... × 1 for n≥1; 0! = 1 by convention.
Analogy
Counting arrangements of n cards: n choices for first, n-1 for second, and so on.
Step-by-step
- Check base case: if n == 0: return 1.
- Otherwise: return n * factorial(n-1).
- Iterative version: start result=1, multiply 1..n.
Common mistakes
- Not handling n=0 (should be 1).
- Stack overflow for large n in recursive version (use iterative or math.factorial).
Practice questions
- Compute 10! manually then verify with math.factorial.
- Find how many trailing zeros 100! has (hint: count factors of 5).
Space
O(n) recursive (stack), O(1) iterative