SwadhyAI Notes

All Java notes

How to Find Factorial in Java

What is Factorial?

Factorial of n (n!) is the product of all positive integers less than or equal to n. Example: 5! = 5 × 4 × 3 × 2 × 1 = 120

Solutions

Method 1: Using For Loop

java
public class Main {
    public static void main(String[] args) {
        int n = 5;
        long factorial = 1;
        
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        
        System.out.println(n + "! = " + factorial);
        // Output: 5! = 120
    }
}

Method 2: Using Recursion

java
public static long factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

// Usage
System.out.println(factorial(5)); // 120
System.out.println(factorial(10)); // 3628800

Method 3: Using Java 8 Streams

java
import java.util.stream.LongStream;

public static long factorial(int n) {
    return LongStream.rangeClosed(1, n)
                     .reduce(1, (a, b) -> a * b);
}

// Usage
System.out.println(factorial(5)); // 120

Did You Know?

0! = 1 by definition! Also, factorials grow extremely fast: 20! = 2,432,902,008,176,640,000. Use long or BigInteger for large numbers!

Watch Out!

Factorials overflow quickly! Use BigInteger for numbers > 20:

java
import java.math.BigInteger;

public static BigInteger factorial(int n) {
    BigInteger result = BigInteger.ONE;
    for (int i = 2; i <= n; i++) {
        result = result.multiply(BigInteger.valueOf(i));
    }
    return result;
}

Real-World Use Cases

  • Permutations: Calculate arrangements (n!)
  • Combinations: Calculate selections (n! / (r! × (n-r)!))
  • Probability: Calculate event probabilities
  • Series expansion: Taylor and Maclaurin series
›Short versionOpen if you only have a minute.
  • n! is the product 1 * 2 * ... * n. 0! is 1 by definition.
  • Start the product at 1. A product that starts at 0 stays 0.
  • 12! fits in an int. 13! does not. 20! fits in a long. 21! does not.
  • A negative argument is not defined for this integer recipe.

Factorial

Multiply all positive integers from 1 to n.

Working approach

  • Use a loop for the straightforward version.
  • Return 1 when n is 0.
  • Widen to long or BigInteger when n is not capped below the overflow point.

Walk the sample

  1. Input 5
  2. Product moves 1, 2, 6, 24, 120
  3. The result is 120

The trap

The product wraps and keeps going. After 13! an int result is not the factorial, and nothing in the arithmetic tells the caller.

java
static long factorial(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("negative factorial");
    }
    long product = 1;
    for (int i = 2; i <= n; i++) {
        product = Math.multiplyExact(product, (long) i);
    }
    return product;
}

Which is the first factorial that does not fit in an int?

12! is 479001600, which fits. 13! is 6227020800, which does not.

An int loop that is correct for the sample 5! is already wrong at 13. multiplyExact throws at the first product that will not fit in the type you chose. 21! needs BigInteger even if the accumulator is a long.

Time O(n), space O(1) for the loop. Recursion adds O(n) stack frames.

Easy to get wrong

  • Initializing the product to 0.
  • Staying on int because 5! printed correctly.