views:

576

answers:

4

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?

+11  A: 
sum = sum.add(BigInteger.valueOf(i))

The BigInteger class is immutable, hence you can't change its state. So calling "add" creates a new BigInteger, rather than modifying the current.

Bozho
+13  A: 

BigInteger is immutable. Therefore, you can't change sum, you need to reassign the result of the add method to sum.

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

Additionally, re-evaluate your need for BigInteger, a simple int primitive may be enough.

MarkPowell
int will be enough as long as you don't go over 2^31-1, long will be enough as long as you don't go over 2^63-1.
jhominal
Which, in his example, he won't.
MarkPowell
+3  A: 

BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.

Poindexter
A: 

Other replies have nailed it; BigInteger is immutable. Here's the minor change to make that code work.

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