cc. cc. - 1 year ago 145
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?

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download