Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this self addition equal 0?

Tags:

java

addition

Curious about how fast self addition would grow, I wrote a quick little loop in Java to see:

int count = 1;
while(true){
    System.out.println(count);
    count += count;
}

The output was unexpected:

0
0
0
0
0
...

Why is this? count is initialized to 1, so the inner addition should be doing count + count or 1 + 1. Why is the result 0?

like image 508
ylun.ca Avatar asked Jun 22 '15 21:06

ylun.ca


People also ask

Why is zero the additive identity?

Additive identity is the value when added to a number, results in the original number. When we add 0 to any real number, we get the same real number. For example, 5 + 0 = 5. Therefore, 0 is the additive identity of any real number.

Why is zero the opposite of itself?

All positive numbers have their opposite as the same number with a negative value. And, negative numbers like -1, -2, -3, -4 their opposite will be 1, 2, 3, 4 placed left from 0. All negative numbers have their opposite as the same numbers with positive value. Hence, the opposite of zero is itself.

Is it true that zero is the identity element for addition?

Definition of identity element For example, 0 is the identity element under addition for the real numbers, since for any real number a, a + 0 = a, and 1 is the identity element under multiplication for the real numbers, since a X 1 = a.


1 Answers

The output you've posted is the trailing lines of the output, not the first 30-31 lines. It goes so fast that after the first 31 iterations it goes beyond INT MAX and the addition results in 0. Remember that a signed integer has a max value of 2^31, or 4 bytes with a sign bit.

Instead of while(true) { try while(count>0) {, you will get to see the first few iterations when it wasn't 0.

like image 90
Raman Shrivastava Avatar answered Oct 17 '22 04:10

Raman Shrivastava