An integer giving negative values ​​in java when multiplied using positive numbers

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 that the integer range was crossed. But why does he give the number -ve . I need to inform me of an error. What is the reason for this behavior?

Thanks in advance...

+4
source share
4 answers

You have overflowed the size of a 32-bit integer.

Consider what happens when I equal 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 zeros).

This is actually getting worse! Intermediate calculations will be performed with limited accuracy, and as soon as the multiplication 10 * 10 * 10 * 10 ... overflows, then 10s will be multiplied by a strange negative number and will already be erroneous.

Thus, the number you end up with is not like any arithmetic rules, but it actually makes sense if you know that primitive integers have limited storage.

The solution is to use the 64-bit long and I hope that you do not overflow THAT too, if you do, you will need BigInteger .

+9
source

Java defines integer math as a signed 2s complement mod 2 ^ 32 (for int) and 2 ^ 64 (for long). Therefore, at any time when the result of int multiply is 2 ^ 31 or higher, it wraps up and becomes a negative number. This is exactly how whole math works in java.

Java specification

+5
source

The primitive type is used. Thus, when an integer overflows, it will only print the bits contained in it, which are negative. If you want to get an error, try Integer.

+1
source

As you predicted, you passed an integer range, although you called infinite values ​​(as the sign [most significant bit] is affected).

+1
source

Source: https://habr.com/ru/post/1484123/


All Articles