← Back to libraryQuestion 71 of 273
⌨️Java CodingBeginner

Factorial of a Number

📌 Definition:

Compute n! = n * (n-1) * ... * 1, with 0! = 1.

📖 Detailed Explanation:

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.

💻 Solutions:
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 r
🔑 Key Points:
  • 0! = 1; reject negatives
  • Iterative O(n), no stack risk
  • Recursion needs a clear base case
  • Overflows int at 13!, long at 21!
🌍 Real-World Example:

A compact demonstration of recursion and, crucially, integer-overflow awareness — the boundary bug testers are trained to hunt.

🎯 Scenario-Based Interview Question:

factorial(20) looks right but factorial(25) returns a negative number. Why?

💡 Quick Tip:

Any factorial/Fibonacci question secretly tests whether you notice overflow — mention it unprompted.