basics · beginner · ~15 min
Use a loop to accumulate a product.
Implement unsigned long factorial(int n) for n >= 0. factorial(0) == 1. You may assume the result fits in unsigned long.
Factorial is the simplest non-trivial recursive-or-iterative function. It also overflows fast — 13! overflows int — making it a great teaching example for integer-size choice.
unsigned long factorial(int n) {
/* TODO */
return 0;
}
Returning int (overflows at 13!). Forgetting the 0! = 1 base case. Iterating from 0 instead of 1 (multiplies by 0).
0! must be 1 (by convention). Large n overflows unsigned long long at 21!.
O(n) iterative, O(n) stack depth recursive.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.