javasqr

why is square of $4945932$ coming out to be negative?


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.


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.