The precision is still well maintained even if you iterate through the first 38 numbers. Give it a try if you are not convinced :)
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;
}
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++)
For sure it's useful. But it would be really better if we could use it like any other integer type.
ReplyDeleteBigInteger.ONE + BigInteger.ONE
it's really sad that this won't compile...
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).
ReplyDeleteFor example:
BigInteger val = BigInteger.ONE;
val.add(BigInteger.ONE);