cc. cc. - 7 months ago 48
Java Question

Java: How to use BigInteger?

I have this piece of code, which is not working:

BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 5000; i++) {
if (isPrim(i)) {

The sum variable is always 0. What am I doing wrong?


BigInteger is immutable. The javadocs stat that add() "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change sum, you need to reassign the result of the add method to sum.

sum = sum.add(BigInteger.valueOf(i));