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

后端 未结 16 2216
轻奢々
轻奢々 2020-12-05 00:14

What are the fastest divisibility tests? Say, given a little-endian architecture and a 32-bit signed integer: how to calculate very fast that a number is divisible by 2,3,4,

16条回答
  •  天涯浪人
    2020-12-05 01:05

    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.

提交回复
热议问题