Often big numbers become negative

user2435678 picture user2435678 · Jun 20, 2013 · Viewed 13.4k times · Source

Since I started using eclipse for project euler, I noticed that big numbers sometime become a seemingly random negative numbers. I suppose this has something to do with passing the boudry of the type.

I'll be glad if you could explain to me how these negative numbers are generated and what is the logic behind it. Also, how can I avoid them (preferable not with BigInteger class). Danke!=)

Answer

Goatcat picture Goatcat · Jun 20, 2013

This image shows what you're looking for. In your case it's obviously larger numbers, but the principle stays the same.

Examples of limits in java are:
int: −2,147,483,648 to 2,147,483,647.
long: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807


In the image 0000, 0001 etc, shows the binary representation of the numbers.

Image explaining two's complement

EDIT: In project euler you often have to think of a way to work around the lagre numbers. The problems are designed with numbers that big so that you can't use the ordinary way of problem solving. However, if you find that you really need to use them, i suggest studying BigInteger anyway. You will find it useful in the long run, and it's not all that complicated. Here is a link with lots of understandable examples: BigInteger Example