Modulus equals zero anyone?
So what? It works and it’s better than precompiling a list of all known even and odd numbers, and expecting a computer to iterate through a whole list every time it wants to check the value of something.
The stupid trig tables are just as problematic and it’s why graphics chips use other geometric functions instead. It’s just better to use a modulus.
If only you could do something like…
def IsEven(number): return number % 2 == 0
Just in case anyone was looking for a decent way to do it…
if (((number/2) - round(number/2)) == 0) return true;
return false;
Or whatever the rounding function is in your language of choice.
EDIT: removed unnecessary else.
number % 2 == 0
and
(number & 0b1) == 0
Are the only sane ways to do this. No need to floor. Although If its C and you can’t modulo floats then (number/2 == floor(number/2))
If you are using floats, you really do not want to have an isEven function …
Whats the alternative a macro? An inline function is perfectly fine for checking if a nunber is even. Compiler will probably optimize it to a single and instruction.
Recently there was a thread trying to declare PHP obsolete.
Hard to beat this in efficiency:
function is_even($num) {
return $num % 2 === 0;
}
That said, this should work similarly in most languages.
Except maybe in C++ where the makers must have found some bit-fucking method that saves 0.02ms
Binary is indeed the easiest and most straightforward way to see number parity. You only need to check one bit.