How to use BigInteger?

cc. picture cc. · Nov 23, 2009 · Viewed 336.6k times · Source

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)) {
        sum.add(BigInteger.valueOf(i));
    }
}

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

Answer

MarkPowell picture MarkPowell · Nov 23, 2009

BigInteger is immutable. The javadocs states 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 variable.

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