Factorial
Return n! — the product of every integer from 1 to n.
- 0! is 1.
- n stays within 0..12, so the result always fits in a 32-bit int.
factorial(n: int) → int
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int factorial(int n) {
}
Worked examples
| Call | Result |
|---|---|
factorial(0) | 1 |
factorial(1) | 1 |
factorial(5) | 120 |
factorial(10) | 3628800 |
Hint
Start an accumulator at 1 and multiply up to n. A loop is plenty.
Reference solution in Java
int factorial(int n) {
int acc = 1;
for (int i = 2; i <= n; i++) acc *= i;
return acc;
}