Compute n! = n * (n-1) * ... * 1, with 0! = 1.
Iterative multiplication is O(n) and safest; recursion (n * factorial(n-1), base case n <= 1) is elegant and often requested. Reject negatives. Results overflow fixed-width integers quickly (13! exceeds int, 21! exceeds long), so use big integers for large n.
public static long factorial(int n) {
if (n < 0) throw new IllegalArgumentException("n >= 0");
long r = 1;
for (int i = 2; i <= n; i++) r *= i;
return r;
}function factorial(n) {
if (n < 0) throw new Error('n >= 0');
let r = 1n; // BigInt for large n
for (let i = 2; i <= n; i++) r *= BigInt(i);
return r;
}def factorial(n):
if n < 0:
raise ValueError('n >= 0')
r = 1
for i in range(2, n + 1):
r *= i
return rA compact demonstration of recursion and, crucially, integer-overflow awareness — the boundary bug testers are trained to hunt.
factorial(20) looks right but factorial(25) returns a negative number. Why?
Any factorial/Fibonacci question secretly tests whether you notice overflow — mention it unprompted.