How to divide an odd number to leave two integers?
The "smaller half" of int x
is x/2
. The "bigger half" is x/2 + x%2
or x - x/2
.
Note that "smaller" and "bigger" refer to the absolute value, so in the case of negative x
, bigger < smaller
.
Of course, if x
is always odd and positive, then x%2
will be 1
and the bigger half can also be computed as x/2 + 1
.
This would be my recommended way:
int low = floor(x / 2.0f);
int high = ceil(x / 2.0f);
I find it to be more concise than the x/2 + x%2
version.
This version also benefits from the fact that the output will be correct if you happen to run it using an even number.
EDIT:
People seemed to complain about me using floating point for integers, well here is a completely bitwise based version:
int a = 9;
int b = a >> 1;
int c = b | (a & 0x1);
The only caveat with #2 is that if the input is negative, the results will not be what is expected.
What about this?
int a = 9;
int c = a/2;
int b = a-c;