问题
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?
回答1:
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));
回答2:
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.
回答3:
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));
}
}
回答4:
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));
回答5:
BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.
回答6:
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
回答7:
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));
回答8:
Biginteger
is an immutable class.
You need to explicitly assign value of your output to sum like this:
sum = sum.add(BigInteger.valueof(i));
回答9:
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.
来源:https://stackoverflow.com/questions/1783912/how-to-use-biginteger