How will you calculate factorial of a large number in Java

Munish Chandel | April 07, 2019 at 10:41 PM | 92 views


Primitive integer is of 4 bytes signed type in Java, so can hold max value of 2147483647. If any calculation demands to store a larger number than this, Java provides BigInteger class to store that. BigInteger can theoretically hold a value limited by your computer memory, thus BigInteger can be used to hold factorial of a large number. Below is the simple illustration of using BigInteger Class for 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
}


You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.4 by Munish Chandel
You may also be interested in..
Generic placeholder image
ebook PDF - Cracking Spring Microservices Interviews for Java Developers

Similar Articles:
  1. Java 8 – HijrahDate, How to calculate the Ramadan date
  2. How to find if the Linked List contains any Cycle/Loop
  3. How will you calculate factorial of a large number in Java
  4. Generate Random Numbers in a range using Java 8
  5. What is difference between JDK JRE and JVM
  6. Difference between Comparable and Comparator in Java with Examples
  7. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications

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