Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

Given a non-negative integer n, factorial is the product of all positive integers less than or equal to n.

In this quick tutorial, we’ll explore different ways to calculate factorial for a given number in Java.

2. Factorial for Numbers up to 20

2.1. Using a for Loop

Let’s see a basic factorial algorithm using a for loop:

public long factorialUsingForLoop(int n) {
    long fact = 1;
    for (int i = 2; i <= n; i++) {
        fact = fact * i;
    }
    return fact;
}

The above solution will work fine for numbers up to 20. But, if we try something bigger than 20, then it will fail because results would be too large to be fit into a long, causing an overflow.

Let’s see a few more, noting that each of these will only work for small numbers.

2.2. Using Java 8 Streams

We can also use the Java 8 Stream API to calculate factorials quite easily:

public long factorialUsingStreams(int n) {
    return LongStream.rangeClosed(1, n)
        .reduce(1, (long x, long y) -> x * y);
}

In this program, we first use LongStream to iterate through the numbers between 1 and n. We then used reduce(), which uses an identity value and accumulator function for the reduction step.

2.3. Using Recursion

And let’s see another example of a factorial program, this time using recursion:

public long factorialUsingRecursion(int n) {
    if (n <= 2) {
        return n;
    }
    return n * factorialUsingRecursion(n - 1);
}

2.4. Using Apache Commons Math

Apache Commons Math has a CombinatoricsUtils class with a static factorial method that we can use to calculate the factorial.

To include Apache Commons Math, we’ll add the commons-math3 dependency into our pom:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>

Let’s see an example using the CombinatoricsUtils class:

public long factorialUsingApacheCommons(int n) {
    return CombinatoricsUtils.factorial(n);
}

Notice that its return type is long, just like our home-grown solutions.

That means here that if the computed value exceeds Long.MAX_VALUE, a MathArithmeticException is thrown.

To get any bigger, we are going to need a different return type.

3. Factorial for Numbers Greater Than 20

3.1. Using BigInteger

As discussed before, the long datatype can be used for factorials only for n <= 20.

For larger values of n, we can use the BigInteger class from the java.math package, which can hold values up to 2^Integer.MAX_VALUE:

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

3.2. Using Guava

Google’s Guava library also provides a utility method for calculating factorials for larger numbers.

To include the library, we can add its the guava dependency to our pom:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>25.1-jre</version>
</dependency>

Now, we can use the static factorial method from the BigIntegerMath class to calculate the factorial of a given number:

public BigInteger factorialUsingGuava(int n) {
    return BigIntegerMath.factorial(n);
}

4. Conclusion

In this article, we saw a few ways of calculating factorials using core Java as well as a couple of external libraries.

We first saw solutions using the long data type for calculating factorials of numbers up to 20. Then, we saw a couple of ways to use BigInteger for numbers greater than 20.

The code presented in this article is available over on Github.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE