Refer to this website: How to Tell if a Binary Number is Divisible by Three
Basically count the number of non-zero odd positions bits and non-zero even position bits from the right. If their difference is divisible by 3, then the number is divisible by 3.
For example:
15 = 1111
which has 2 odd and 2 even non-zero bits. The difference is 0. Thus 15
is divisible by 3
.
185 = 10111001
which has 2 odd non-zero bits and 3 even non-zero bits. The difference is 1. Thus 185
is not divisible by 3
.
Explanation
Consider the 2^n
values. We know that 2^0 = 1
is congruent 1 mod 3
. Thus 2^1 = 2
is congurent 2*1 = 2
mod 3. Continuing the pattern, we notice that for 2^n
where n is odd, 2^n
is congruent 1 mod 3
and for even it is congruent 2 mod 3
which is -1 mod 3
. Thus 10111001
is congruent 1*1 + 0*-1 + 1*1 + 1*-1 + 1*1 + 0*-1 + 0*1 + 1*-1
mod 3 which is congruent 1 mod 3
. Thus 185 is not divisible by 3.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…