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));
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.
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));
}
}
BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With