# How will you calculate factorial of a large number in Java

Carvia Tech | April 30, 2019 | 1 min read | 118 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)
}
return factorial
}``````

##### 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:
Book you may be interested in..
##### ebook PDF - Cracking Java Interviews v3.5 by Munish Chandel
Book you may be interested in..
##### ebook PDF - Cracking Spring Microservices Interviews for Java Developers
Book you may be interested in..