why is square of $4945932$ coming out to be negative?
Question
I declared an integer int i = 4945932; and its square is coming out to be some negative random number. How is this possible? What am i doing wrong? Help please.Thanks in advance.
La solution
Integer overflow. A Java int cannot be larger than 2,147,483,647; if you try to store a larger number, it overflows.
If you instead use a long
, that can store much larger values, including the one you're trying to store. If you need even larger values, java.math.BigInteger
can store arbitrary-precision integers; the only limit is your computer's memory.
Autres conseils
it happens because of the limit of the int. integer OverFlow.
int can store 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.
if you write int i= square(4945932)
it is 24462243348624 so it will exceed the limit of int so it behaves abnormal.
You can use
long l = 4945932L;
System.out.println(l * l);
BigInteger bi = BigInteger.valueOf(4945932L);
System.out.println(bi.multiply(bi));
prints
24462243348624
24462243348624
You are exceeding the size of an int. You will need to change to a long if you want to square 4945932.