Determine whether a non-negative integer n is divisible by 17 using bitwise operations and simple arithmetic — avoid full integer division where possible.
Use the congruence 16 ≡ −1 (mod 17) to replace division by 17 with a cheap bitwise reduction. Writing n = 16*q + r (so q = n » 4 and r = n & 15) gives
1
n ≡-q +r (mod 17)
Hence n ≡ 0 (mod 17) ⇔ q − r ≡ 0 (mod 17). Repeatedly replacing m by |(m»4) − (m&15)| shrinks m by roughly a factor of 16 each step and preserves divisibility-by-17.
Below are the algebraic steps that justify the reduction:
The final line shows n/17 is integral exactly when floor(n/16) - (n%16) is a multiple of 17. Replacing floor(n/16) with n >> 4 and n%16 with n & 15 yields the bitwise test.
classSolution {
publicbooleanisDivBy17(long n) {
if (n == 0) returntrue;
long m = Math.abs(n);
while (m >= 17) {
long q = m >> 4;
long r = m & 15;
m = Math.abs(q - r);
}
return m == 0 || m == 17;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defis_div_by_17(self, n: int) -> bool:
if n ==0:
returnTrue m = abs(n)
while m >=17:
q = m >>4 r = m &15 m = abs(q - r)
return m ==0or m ==17