# 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)
}
return factorial
}``````

You may also be interested in..
##### ebook PDF - Cracking Java Interviews v3.4 by Munish Chandel
You may also be interested in..

##### Similar Articles:
You may also be interested in..
##### ebook PDF - Cracking Java Interviews v3.4 by Munish Chandel
You may also be interested in..