There are different ways. The simplest is pretty obvious:
int isdivby3(int n) {
if (n < 0) n = -n;
while (n > 0) n -= 3;
return n == 0;
}
But we can improve it. Any number can be represented as follows: ("," means the range inclusive):
Base2 (AKA binary)
(0,1) + 2*(0,1) + 4*(0,1)
Base4
(0,3) + 4*(0,3) + 16*(0,3)
BaseN
(0,N-1) + N*(0,N-1) + N*N*(0,N-1)
Now the trick, the number xis divisible by n-1if and only if the number xin the database nis divisible by n-1. This trick is well known for 9:
1926 = 6 + 2*10 + 9*100 + 1*1000
6+2+9+1 = 8 + 1*10
8+1 = 9 thus 1926 is divisible by 9
3 base4. , 4 - 2, . number(base).
27(10) = 123(4)
Digitsum
12(4)
Digitsum again
3(4) = Divisible!
C:
int div3(int n) {
if (n < 0) n = -n;
else if (n == 0) return 1;
while (n > 3) {
int d = 0;
while (n > 0) {
d += n & 3;
n >>= 2;
}
n = d;
}
return n == 3;
}
.