Factorial of a large number in Java BigInteger

Upasana | October 18, 2020 | 1 min read | 374 views


Primitive integer is of 4 bytes signed type in Java, so can hold max value of 2147483647. If any calculation requires to store a larger number than this, Java provides BigInteger class to handle that scenario.

BigInteger can theoretically hold an arbitrary-precision integer value limited by your computer memory. Thus BigInteger is an ideal candidate for calculating factorial of a large number.

BigInteger Documentation

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two’s-complement notation (like Java’s primitive integer types). BigInteger provides analogues to all of Java’s primitive integer operators, and all relevant methods from java.lang.Math.

Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

Factorial Calculation
import java.math.BigInteger;

public class Main {

    public static void main(String[] args) {
        BigInteger factorial = BigInteger.ONE;

        int n = 100;

        for (int i = 1; i <= n; i++) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }

        System.out.println("factorial = " + factorial);
    }
}
Result will be something like this -
factorial = 93326215443944152681699......

The same program in Kotlin will look like below:

Factorial - Kotlin version
import java.math.BigInteger

fun factorial(num: BigInteger): BigInteger {
    var factorial = BigInteger.ONE
    var i = BigInteger.ONE
    while (i <= num) {
        factorial = factorial.multiply(i)
        i = i.add(BigInteger.ONE)
    }
    return factorial
}

Top articles in this category:
  1. Discuss internals of a ConcurrentHashmap (CHM) in Java
  2. Given a collection of 1 million integers, all ranging between 1 to 9, sort them in Big O(n) time
  3. can we write a java method that swaps two integers
  4. Find missing numbers in 4 billion unique numbers with 50MB RAM
  5. Generate Random Numbers in a range using Java 8
  6. Precision and scale for a Double in java
  7. Is Java Pure Object Oriented Language?

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.