Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer giving negative values in java in multiplication using positive numbers [duplicate]

Tags:

java

integer

public class Test {

    public static void main(String[] args) {    
        int sum=0;
        for(int i=1;i<10;i++)
            sum = sum+i*i*i*i*i*i*i*i*i*i;
        System.out.println(sum);                

    }    
}

OUTPUT:619374629

    for(int i=1;i<10;i++)
        sum = sum+i*i*i*i*i*i*i*i*i*i*i;
    System.out.println(sum);        

       OUTPUT:
        -585353335

In the second output i thought the integer range crossed.But why it is giving -ve number.It need to give me an error.What is the reason for this behaviour?

Thanks in advance...

like image 214
PSR Avatar asked Dec 01 '22 21:12

PSR


2 Answers

You have overflowed the size of a 32 bit integer.

Consider what happens when i is equal to 10:

sum = sum + 100000000000 //1 with 11 zeroes

But the maximum positive number that can be stored in a 32 bit integer is only about 2 billion (2 with nine zeroes).

In fact, it gets even worse! The intermediate calculations will be performed with limited precision, and as soon as the multiplication of 10*10*10*10... overflows, then the 10s will be being multiplied with a weird negative number, and be already wrong.

So the number you end up with is not seeming to follow any rules of arithmetic, but in fact it makes perfect sense once you know that primitive integers have limited storage.

The solution is to use 64-bit long and hope you don't overflow THAT too, if you do then you need BigInteger.

like image 125
Patashu Avatar answered Dec 04 '22 12:12

Patashu


Java defines integer math as signed 2s-complement mod 2^32 (for int) and 2^64 (for long). So any time that the result of an int multiply is 2^31 or higher, it wraps around and becomes a negative number. That's just the way integer math works in java.

Java spec

like image 44
Chris Dodd Avatar answered Dec 04 '22 12:12

Chris Dodd