How will you calculate factorial of a large number in Java

Carvia Tech | April 30, 2019 | 1 min read | 165 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. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock
  2. What is ThreadLocal in Java, where will you use this class
  3. Diamond Problem of Inheritance in Java 8
  4. What do you understand by Java Memory Model?
  5. How will you implement your custom threadsafe Semaphore in Java
  6. How will you implement a Blocking Queue in Java
  7. How to implement Thread pool in Java without executor framework



Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info