If I have an odd number, how would I divide it in two and leave two integers, with the first being one more than the second. For instance 9 would produce 5 and 4?
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
.
What about this?
int a = 9;
int c = a/2;
int b = a-c;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With