Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use BigInteger?

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.