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#.

707 Views
    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;            
    }

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

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

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;
}

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