Live data from Hacker News

Test if a number is even

ubuntuincident.wordpress.com

1–10 of 68 posts

Re: Test if a number is even

#5

> I think the optimizer recognizes modulo 2 and converts it to bitwise AND. You don't have to guess, you could turn or O3 or look at the disassembly.

Interestingly, not only do both versions emit the same assembly, but clang both autovectorizes and unrolls the loop:

https://godbolt.org/z/qxsKWfz9s

Re: Test if a number is even

#6
Optimizing compilers have been able to recognize pretty complicated patterns for many years.

For instance if you're making a loop to count the bits that are set in a number, the compiler can recognize the entire loop and turn it into a single popcnt instruction (e.g. https://lemire.me/blog/2016/05/23/the-surprising-cleverness-... )

Re: Test if a number is even

#7

I like the algorithms that are the opposite of this where they try to find the slowest possible way to determine if a number is even.

https://github.com/blackburn32/serverlessIsEven "A serverless implementation of isEven. Now you can know if your numbers are even, even at mass scale."

Re: Test if a number is even

#10
> I think the optimizer recognizes modulo 2 and converts it to bitwise AND.

A quick check in the compiler explorer (godbolt.org) confirms that this is indeed true for GCC on x86_64 and aarch64, but not for clang on the same (clang does optimize it with -O3).

Post reply on HN