Tuesday, September 8, 2009

Usefulness of BigInteger

It's way much better than Integer, the primitive type; simply because we won't be restricted with arithmetic overflow issue. An example is in this method to compute factorial.

public static BigInteger factorial(int n){
BigInteger result = BigInteger.ONE;
for (int count = 1; count <= n; count++) {
result = result.multiply(BigInteger.valueOf(count));
}
return result;
}
The precision is still well maintained even if you iterate through the first 38 numbers. Give it a try if you are not convinced :)
UPDATE: there is a fundamental flaw in this loop. In the previous code, I demonstrated for (int count = 1; count < n; count++). It has changed to for (int count = 1; count <= n; count++)

2 comments:

  1. For sure it's useful. But it would be really better if we could use it like any other integer type.

    BigInteger.ONE + BigInteger.ONE

    it's really sad that this won't compile...

    ReplyDelete
  2. Jonas, you are correct that it doesn't compile if we use the '+' operand. We'll have to use .add() for BigInteger. So in your case it would be .add(BigInteger.ONE).

    For example:
    BigInteger val = BigInteger.ONE;
    val.add(BigInteger.ONE);

    ReplyDelete