Sunday, February 1, 2015

Java BigInteger Example How to use BigInteger Factorial of large data Convert int to BigInteger and BigInteger to int

All most all number data type in Java has some limit but what you will do if you have to do some calculation on big data like calculate factorial of 100 or 500 :)

There is no theoretical limit. The BigInteger class allocates as much memory as it needs to hold all the bits of data it is asked to hold.

If you are working with values that cannot fit into a long or a double then you will need to use a reference type like BigInteger.

It does not support addition by + like other number datatype in java. For that addition you have to call add() method.

You can use bigInteger for int, long, double etc. Please check this document link.

Convert from int to BigInteger

BigInteger newdata = BigInteger.valueOf(20);

Convert from BigInteger to int
int intdata = newdata.intMax.intValue());  

Factorial example for big data:

import java.util.Date;
import static java.lang.System.out;  
import java.math.BigInteger;

public class BigFactorial {

 public static void main(String[] args) {
BigFactorial heck = new BigFactorial();

private BigInteger fact(BigInteger n){
   if(n==BigInteger.valueOf(0) || n==BigInteger.valueOf(1) )return BigInteger.valueOf(1);
return n.multiply(fact(n.subtract(BigInteger.valueOf(1))));


No comments:

Post a Comment

You can put your comments here (Either feedback or your Question related to blog)