Tuesday, February 2, 2016

How will you calculate a Large Factorial in Java?

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.
  1. import java.math.BigInteger;
  2. public class Main {
  3. public static void main(String[] args) {
  4. BigInteger factorial = BigInteger.ONE;
  5. int n = 100;
  6. for (int i = 1; i <= n; i++) {
  7. factorial = factorial.multiply(BigInteger.valueOf(i));
  8. }
  9. System.out.println("factorial = " + factorial);
  10. }
  11. }
Result will be something like this -
  1. factorial = 93326215443944152681699......
 
See original article at -
http://javainterviews.scribbleit.in/algorithms-ds/calculate-factorial-of-large-number-java-big-integer/p/A0Z5LA

1 comment:

  1. 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

Your comment will be published after review from moderator