Given a non-negative integer n, compute n! (n factorial), defined as the product of all positive integers up to n:
n! = n * (n-1) * ... * 2 * 1, with 0! = 1.
Factorial grows very quickly; for moderate n the result will overflow fixed-size integer types. Use arbitrary-precision types (e.g., Python int, Java BigInteger) when large n must be supported.
Two standard ways to compute factorial are shown below: recursion and iterative multiplication. Both compute the same result; recursion is concise but can overflow the call stack for deep recursion, while iteration is iterative and typically preferred in production.
Compute the product 1 * 2 * ... * n using a simple loop β avoids recursion depth issues and is straightforward to write for arbitrary-precision types.
classSolution {
public:unsignedlonglong factorial_iter(unsignedint n) {
unsignedlonglong ans =1ULL;
for (unsignedint i =2; i <= n; ++i) ans *= i;
return ans;
}
};
import java.math.BigInteger;
classSolution {
public BigInteger factorialBig(int n) {
BigInteger ans = BigInteger.ONE;
for (int i = 2; i <= n; i++) ans = ans.multiply(BigInteger.valueOf(i));
return ans;
}
}
1
2
3
4
5
6
7
8
9
import java.math.BigInteger
classSolution {
funfactorialBig(n: Int): BigInteger {
var ans = BigInteger.ONE
for (i in2..n) ans = ans.multiply(BigInteger.valueOf(i.toLong()))
return ans
}
}
1
2
3
4
5
6
classSolution:
deffactorial_iter(self, n: int) -> int:
ans =1for i in range(2, n +1):
ans *= i
return ans