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?
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?
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.
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.
BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.
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));
}
}