BigInteger returning negative numbers [duplicate]

不羁的心 提交于 2019-12-13 22:46:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!