Make a given number odd or even


There are times when you need to make sure your counter starts at an odd or even number.

Even is pretty simple - counter = counter + modulus(counter). If counter is even it stays, if it's odd it gets incremented by 1.

Odd is a bit more complicated - counter = counter + modulus(counter + 1), If counter is odd it stays, if it's even it gets incremented by 1.

if you're in danger of counter being the max value you can always subtract instead.

These basic algorithms should work for any language that has a modulus operator/function.

I've included a simple example in C#.

About the Author
    static int MakeOddOrEven(int num, bool odd = true)
        int offset = odd ? 1 : 0;
        int direction = 1;
        if(num == int.MaxValue)
            direction = -1;
        return num += ((num + (offset * direction)) % 2) * direction;            
JamesCherrill 4,304 Most Valuable Poster Moderator Featured Poster

How about ANDing it with 0xFFFFFFFE for even, ORing it with 0x00000001 for odd?

tinstaafl 1,131 Posting Maven

That would work as well, i suppose. I think, for most people, though, the modulus operator would be more intuitive.

JamesCherrill 4,304 Most Valuable Poster Moderator Featured Poster

maybe I'm just an old-timer who started with binary, but for me flipping the last bit just screams odd/even, but the modulus arithmetic I had to think about. Guess it all depends where you'e coming from

static int MakeOddOrEven(int num, boolean odd) { // java 
    return odd ? num | 1 : num & 0xFFFFFFFE;
jimmichaels29 0 Newbie Poster

try even=modulus(counter,2)==0

Xozz 89 Junior Poster

Hi. The reason I reply to this topic is that I want to become an active member of Daniweb :P I've been putting a lot of questions on here and this topic shows me another way to "contribute". I know the difference between even and odd. Greetings

holisticgroup19 -6 Newbie Poster

i think even modulus should be ==to 1 instead of 0

JamesCherrill commented: No. It was right the first time. Hope your taxi driving is better than your logic -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.