Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide an odd number to leave two integers?

Tags:

math

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?

like image 297
cannyboy Avatar asked Mar 23 '12 15:03

cannyboy


3 Answers

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.

like image 143
Fred Foo Avatar answered Nov 13 '22 09:11

Fred Foo


What about this?

int a = 9;
int c = a/2;
int b = a-c;
like image 5
mouviciel Avatar answered Nov 13 '22 11:11

mouviciel


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.

like image 3
Richard J. Ross III Avatar answered Nov 13 '22 09:11

Richard J. Ross III