问题
why this math return negative numbers for some numbers:
int x = 351;
String bigValue= ((50*x*x*x-150*x*x+400*x)/3) + "";
BigInteger resultInteger = new BigInteger(bigValue);
System.out.println(resultInteger);
result -> 714612600
but if i use 352
result -> -710900565
for x=500 -> 639244234
WHY?
回答1:
This line here:
(50*x*x*x-150*x*x+400*x)/3
Is using integers, which can overflow. If an integer hits the max (2^31-1), it will overflow to -2^31.
You need to use BigIntegers here, something like this:
Biginteger bx = new BigInteger(x);
BigInteger new BigInteger(50).multiply(bx.pow(3)).multiply(new BigInteger(-150))
.multiply(bx.pow(2)).multiply(new BigInteger(400)).multiply(bx).divide(3);
来源:https://stackoverflow.com/questions/24223440/biginteger-returning-negative-numbers