BigInteger返回负数 [英] BigInteger returning negative numbers

查看:807
本文介绍了BigInteger返回负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此数学方法对某些数字返回负数:

why this math return negative numbers for some numbers:

int x = 351;

int x = 351;

    String bigValue= ((50*x*x*x-150*x*x+400*x)/3) + "";
    BigInteger resultInteger = new BigInteger(bigValue);
    System.out.println(resultInteger);

结果-> 714612600

result -> 714612600

但是如果我使用352

but if i use 352

结果-> -710900565

result -> -710900565

对于x = 500-> 639244234

for x=500 -> 639244234

为什么?

推荐答案

此行:

(50*x*x*x-150*x*x+400*x)/3

使用整数,该整数可能溢出.如果整数达到最大值(2 ^ 31-1),则会溢出到-2 ^ 31.

Is using integers, which can overflow. If an integer hits the max (2^31-1), it will overflow to -2^31.

您需要在此处使用BigIntegers,如下所示:

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);

这篇关于BigInteger返回负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆