Search code examples
bit-manipulationpseudocodeinteger-arithmeticmodular-arithmetic

AND vs. MOD for ODD


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.


Solution

  • With modern compiler optimization, I would go for source code clarity in this case.

    Look for example at the executable code generated for the AND case (https://godbolt.org/z/sPqM6f) vs. the code generated for the MOD case (https://godbolt.org/z/vM6r3q) with the GCC C++ compiler. They are identical. Not just similar, but identical because the compiler recognized the MOD 2 operation as a special case which can be optimized.

    As compiler optimization gets better and better and assembler instructions get more and more involved, I personally tend to go more for source code (including pseudo code) clarity than trying to nudge a compiler into something which I think is an optimization.