For some reason, BigInteger isn’t working as I’d like. I’m doing BigVariable.add(BigVariable), but it won’t add. It the result is always the value it’s initialized to. Anyone know what I’m missing? Thanks in advance
The code is for project euler 48
import java.math.BigInteger;
public class tuna {
public static void main(String[] args) {
BigInteger result = BigInteger.ZERO;
for(int i= 1; i <= 1000; i++)
result.add( bigPow(BigInteger.valueOf(i), i) );
System.out.println(result);
}
public static BigInteger bigPow(BigInteger number, int pow){
if(pow < 1)
throw new RuntimeException("bigPow can't handle exponents lower than 1");
if (pow == 1)
return number;
return number.multiply( bigPow(number, pow-1) );
}
}
Try:
instead of:
You need to do this because BigInteger is immutable (Immutable arbitrary-precision integers). So you need to reassign the result.
add