I was looking for a value of i
where i==i+1
should always be true
. Some others used double
and float
to find a solution to the problem.
I was trying to answer to a question on stack overflow. And thought about integers, trying to see if that could be possible too.
But while manipulating Integer.MAX_VALUE
and Integer.MIN_VALUE
many times, I found this strange behavior:
Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
But Integer.MAX_VALUE * 2 == -2
and Integer.MAX_VALUE * 4 == -4
This happens only if I use even values like (2,4,6,8,10,12...). When I use odd values except 1, this happens:
Integer.MAX_VALUE * n == Integer.MAX_VALUE - n + 1
where n != Integer.MIN_VALUE
and n > Integer.MIN_VALUE
Why is this behaving so? Is there something I am missing?
EDIT: I saw someone flagging the question as duplicate but navigating to the referred link, my question is different.
If it overflows, it goes back to the minimum value and continues from >there. If it underflows, it goes back to the maximum value and continues >from there.
I've carefully read answers from there but none of them explained why:
Integer.MAX_VALUE*x
should be -x
if x is an even number and Integer.MAX_VALUE*y
should be Integer.MAX_VALUE-y+1
if y is an odd number.
That's exactly what is confusing me the most.