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?
This question is related to
java
biginteger
BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.
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.
Yes it's Immutable
sum.add(BigInteger.valueOf(i));
so the method add() of BigInteger class does not add new BigIntger value to its own value ,but creates and returns a new BigInteger reference without changing the current BigInteger and this is what done even in the case of Strings
Since you are summing up some int values together, there is no need to use BigInteger. long
is enough for that. int
is 32 bits, while long
is 64 bits, that can contain the sum of all int values.
Actually you can use,
BigInteger sum= new BigInteger("12345");
for creating object for BigInteger class.But the problem here is,you cannot give a variable in the double quotes.So we have to use the valueOf() method and we have to store the answer in that sum again.So we will write,
sum= sum.add(BigInteger.valueOf(i));
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.
You need to explicitly assign value of your output to sum like this:
sum = sum.add(BigInteger.valueof(i));
java.math.BigInteger
is an immutable class so we can not assign new object in the location of already assigned object. But you can create new object to assign new value like:
sum = sum.add(BigInteger.valueOf(i));
Source: Stackoverflow.com