Java Factorial Program with Loop, Recursion and BigInteger

The factorial of n is n x (n-1) x ... x 1, for example 5! = 120. It grows very fast: 21! is already too big for a long.

Loop and recursion

public class Main {
    static long factorialLoop(int n) {
        long result = 1;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    static long factorialRec(int n) {
        return n <= 1 ? 1 : n * factorialRec(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(factorialLoop(5));
        System.out.println(factorialRec(10));
        System.out.println(factorialLoop(20));     // the biggest one for a long
        System.out.println(factorialLoop(21));     // overflow: wrong value, no error
    }
}
Output

120
3628800
2432902008176640000
-4249290049419214848

BigInteger for big results

import java.math.BigInteger;

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

    public static void main(String[] args) {
        System.out.println(factorial(21));
        System.out.println(factorial(30));
        BigInteger f100 = factorial(100);
        System.out.println(f100.toString().length() + " digits");
        System.out.println(f100.toString().substring(0, 20) + "...");
    }
}
Output

51090942171709440000
265252859812191058636308480000000
158 digits
93326215443944152681…

BigInteger has no size limit. It is slower than long, so use it only when you need it.

Check the negative input

public class Neg {
    static long factorial(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Factorial is not defined for negative numbers: " + n);
        }
        return n <= 1 ? 1 : n * factorial(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(factorial(-3));
    }
}
Output

Exception in thread "main" java.lang.IllegalArgumentException: Factorial is not defined for negative numbers: -3
at Neg.factorial(Neg.java:4)
at Neg.main(Neg.java:10)

Related: Java Recursion and Java Exceptions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.