How do I divide an odd number to leave two integers?

If I have an odd number, how would I split it in two and leave two integers, with the first being the second than the second. For example, will 9 produce 5 and 4?

+4


source to share


5 answers


"less than half" int x

is equal x/2

. "Bigger half" - x/2 + x%2

or x - x/2

.

Note that the "less than" and "greater" refers to the absolute value, so in the case of negative x

, bigger < smaller

.



Of course, if x

it is always odd and positive, then it x%2

will 1

, and the greater half can also be calculated as x/2 + 1

.

+12


source


How about this?



int a = 9;
int c = a/2;
int b = a-c;

      

+5


source


For people who use microcontrollers where /

u %

are terrible expenses :-)

This shows an alternative method using shift >>

and &

, which are sometimes cheaper:

#include <stdio.h>

int main (int argc, const char * argv[]) {
    const int iplus = 9;
    const int iminus = -9;

    printf("iplus=%d iminus=%d\n", iplus, iminus);

    printf("(iplus >> 1)=%d ((iplus >> 1) + (iplus & 1))=%d\n", iplus >> 1, (iplus >> 1) + (iplus & 1));
    printf("(iminus >> 1)=%d ((iminus >> 1) + (iminus & 1))=%d\n", iminus >> 1, (iminus >> 1) + (iminus & 1));

    return 0;
}

      

Output:

iplus=9 iminus=-9
(iplus >> 1)=4 ((iplus >> 1) + (iplus & 1))=5
(iminus >> 1)=-5 ((iminus >> 1) + (iminus & 1))=-4

      

Accordingly, Does ANSI C or ISO C indicate -5% 10?

There is a difference in terms of behavior /

between C89 and C99, and in particular C89 '/

with one negative number may return positive or negative, but C99 is negative.

+3


source


This would be my recommended way:

int low = floor(x / 2.0f);
int high = ceil(x / 2.0f);

      

I find this to be more concise than the version x/2 + x%2

. This version also benefits from the fact that the result is correct if you performed it using an even number.

EDIT:

People seemed to be complaining to me about using floating point numbers for integers, and here is the bit-based version:

int a = 9;

int b = a >> 1;
int c = b | (a & 0x1);

      

C # 2's only caveat is that if the input is negative, the results will not be as expected.

+2


source


I thought the accepted answer was in the stadium but unclear. If you want to copy and paste the code, this would be the best solution in my opinion

var number = 11;
var halfRoundedUp = (number % 2) ? number/2 + .5 : number/2;
var halfRoundedDown = (number % 2) ? number/2 - .5 : number/2;
alert(halfRoundedUp +" "+ halfRoundedDown);

      

+1


source







All Articles