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.

Result will be something like this -

`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);`

`}`

`}`

`factorial = 93326215443944152681699......`

`See original article at -`

`http://javainterviews.scribbleit.in/algorithms-ds/calculate-factorial-of-large-number-java-big-integer/p/A0Z5LA`

This is a good solution. But why aren't you using Streams to solve your problems. They are more concise and efficient than Iterators.

ReplyDelete