Justin Robbins

Ranch Hand

Posts: 121

2

Fred Kleinschmidt

Bartender

Posts: 560

9

posted 1 year ago

The "x modulo 2 is zero if and only if x is even" idea is the simplest way to do it, if you want other programmers who you haven't met yet to understand it. So that's how I would always do it.

However if you are comfortable with bit-fiddling you can start with the fact that numbers whose least significant bit is zero are always even. So a modified version of your code might look like:

This might even be faster, since integer division takes longer than a simple bit calculation. But only by a tiny amount, and it's not impossible that the run-time might optimize division by 2 into a bit calculation. I wouldn't even consider that code unless I expected my application to be spending most of its time deciding whether numbers were even or not, because I find it a lot less readable.

However if you are comfortable with bit-fiddling you can start with the fact that numbers whose least significant bit is zero are always even. So a modified version of your code might look like:

This might even be faster, since integer division takes longer than a simple bit calculation. But only by a tiny amount, and it's not impossible that the run-time might optimize division by 2 into a bit calculation. I wouldn't even consider that code unless I expected my application to be spending most of its time deciding whether numbers were even or not, because I find it a lot less readable.

Campbell Ritchie

Marshal

Posts: 55715

163