Learning outcomes
By the end of this lecture, you should be able to:- define factorial mathematically
- implement factorial using
while - trace factorial loops for any
n - handle edge cases (
0, negative input)
Factorial definition
n! = n * (n-1) * (n-2) * ... * 10! = 1
5! = 1203! = 6
Standard while solution
Why initialize fact = 1
- multiplicative identity is
1 - starting at
0would make final answer always0
Dry run for n = 5
| Iteration | i | fact before | fact *= i | fact after |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 * 1 | 1 |
| 2 | 2 | 1 | 1 * 2 | 2 |
| 3 | 3 | 2 | 2 * 3 | 6 |
| 4 | 4 | 6 | 6 * 4 | 24 |
| 5 | 5 | 24 | 24 * 5 | 120 |
Compact variant
Common mistakes
fact = 0(wrong start)while i < n(misses multiplying byn)- forgetting
i += 1 - not handling negative
n
Exam hints and traps
- always remember
0! = 1 - for
n = 1, output is1 - negative inputs are invalid for standard factorial
Practice
- Write factorial using descending loop (
i = ndown to1). - Predict output for
n = 0. - Fix bug:
Answer key
1- condition should be
while i <= n:
