W WolfCode · CSC 141

Factorial

阶乘

≈ 15 min · python-recursion · Open in WolfCode

The most-quoted recursion in computer science. Two-line body, induction-style correctness.

Python · runnable

Trace once, for understanding

factorial(3)        → 3 * factorial(2)
  factorial(2)      → 2 * factorial(1)
    factorial(1)    → 1 * factorial(0)
      factorial(0)  → 1                          ← BASE
    factorial(1)    → 1 * 1 = 1
  factorial(2)      → 2 * 1 = 2
factorial(3)        → 3 * 2 = 6