1

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?

user2582318
  • 1,607
  • 5
  • 29
  • 47

1 Answers1

6

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);
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75