Fast divisibility tests (by 2,3,4,5,.., 16)?

In every case (including divisible by 2):

if (number % n == 0) do();

Anding with a mask of low order bits is just obfuscation, and with a modern compiler will not be any faster than writing the code in a readable fashion.

If you have to test all of the cases, you might improve performance by putting some of the cases in the if for another: there’s no point it testing for divisibility by 4 if divisibility by 2 has already failed, for example.

Leave a Comment