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

后端 未结 16 2191
轻奢々
轻奢々 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 00:58

    This probably won't help you in code, but there's a neat trick which can help do this in your head in some cases:

    For divide by 3: For a number represented in decimal, you can sum all the digits, and check if the sum is divisible by 3.

    Example: 12345 => 1+2+3+4+5 = 15 => 1+5 = 6, which is divisible by 3 (3 x 4115 = 12345).

    More interestingly the same technique works for all factors of X-1, where X is the base in which the number is represented. So for decimal number, you can check divide by 3 or 9. For hex, you can check divide by 3,5 or 15. And for octal numbers, you can check divide by 7.

提交回复
热议问题