One of the most basic operations in programming is figuring out whether the given x
is even or odd. The common way to do that is:
ODD(x) = x MOD 2 == 1
The other less popular variant being:
ODD(x) = x AND 1 == 1
It is widely known that those ~bit hacks~ are faster than division. I wonder whether anyone has ever run into a case where the substitution of MOD 2
for AND 1
brought about a significant optimization.
What are the PROs and CONs of each approach, besides time?
Personally, I would probably point out that MOD m
works for any m
, whereas AND 1
cannot be adjusted for other moduli.