basics · beginner · ~15 min
Use a loop to accumulate a product.
Compute n! = 1 * 2 * ... * n with a loop.
Implement unsigned long factorial(int n) that returns the factorial of n. No main — the grader calls it.
One int argument n with n >= 0. You may assume the result fits in unsigned long.
The product 1 * 2 * ... * n as an unsigned long. By definition factorial(0) is 1.
factorial(0) -> 1
factorial(5) -> 120
factorial(10) -> 3628800
factorial(0) and factorial(1) are both 1.unsigned long are tested.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.
One int argument n with n >= 0.
The factorial of n as an unsigned long; factorial(0) is 1.
Assume the result fits in unsigned long.
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.