Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Often big numbers become negative

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!=)

like image 963
user2435678 Avatar asked Jun 20 '13 16:06

user2435678


People also ask

Can the largest number be negative?

So, −1 is the largest of all the negative numbers. Therefore, In conclusion we can say that −1 is the largest negative number. Note: It is also very important to note that one may think that just like the positive integers, the greatest negative integer will be tending to the negative of infinity.

Why is the biggest negative number?

Answer: -1 is the greatest negative integer.

Can a long value be negative?

Yes it does support negative values as long as it is not appended after unsigned .

What is a bigger negative number?

When dealing with negative numbers, the number closer to zero is the bigger number.\n \n Zero (0) has the unique distinction of being neither positive nor negative. Zero separates the positive numbers from the negative ones.


2 Answers

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

like image 173
Goatcat Avatar answered Nov 15 '22 14:11

Goatcat


In mathematics numbers are infinite. However in computers they are not. There is MAX_VALUE for each int-like type: int, short, long. For example Integer.MAX_VALUE. When you try to increase number more than this value the number becomes negative. This way the internal binary representation of numbers work.

int i = Integer.MAX_VALUE;
i++; // i becomes negative. 
like image 32
AlexR Avatar answered Nov 15 '22 13:11

AlexR