Given a number n, write a function that returns true if n is divisible by 9, else false. The most simple way to check for n’s divisibility by 9 is to do n%9.
Another method is to sum the digits of n. If sum of digits is multiple of 9, then n is multiple of 9.
The above methods are not bitwise operators based methods and require use of % and /.
The bitwise operators are generally faster than modulo and division operators. Following is a bitwise operator based method to check divisibility by 9.

[pastacode lang=”cpp” manual=”%23include%3Ciostream%3E%0Ausing%20namespace%20std%3B%0A%20%0A%2F%2F%20Bitwise%20operator%20based%20function%20to%20check%20divisibility%20by%209%0Abool%20isDivBy9(int%20n)%0A%7B%0A%20%20%20%20%2F%2F%20Base%20cases%0A%20%20%20%20if%20(n%20%3D%3D%200%20%7C%7C%20n%20%3D%3D%209)%0A%20%20%20%20%20%20%20%20return%20true%3B%0A%20%20%20%20if%20(n%20%3C%209)%0A%20%20%20%20%20%20%20%20return%20false%3B%0A%20%0A%20%20%20%20%2F%2F%20If%20n%20is%20greater%20than%209%2C%20then%20recur%20for%20%5Bfloor(n%2F9)%20-%20n%258%5D%0A%20%20%20%20return%20isDivBy9((int)(n%3E%3E3)%20-%20(int)(n%267))%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0A%20%20%20%20%2F%2F%20Let%20us%20print%20all%20multiples%20of%209%20from%200%20to%20100%0A%20%20%20%20%2F%2F%20using%20above%20method%0A%20%20%20%20for%20(int%20i%20%3D%200%3B%20i%20%3C%20100%3B%20i%2B%2B)%0A%20%20%20%20%20%20%20if%20(isDivBy9(i))%0A%20%20%20%20%20%20%20%20%20cout%20%3C%3C%20i%20%3C%3C%20%22%20%22%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C programming” highlight=”” provider=”manual”/]

Output:

0 9 18 27 36 45 54 63 72 81 90 99
[ad type=”banner”]

How does this work?
n/9 can be written in terms of n/8 using the following simple formula.

n/9 = n/8 - n/72

Since we need to use bitwise operators, we get the value of floor(n/8) using n>>3 and get value of n%8 using n&7. We need to write above expression in terms of floor(n/8) and n%8.
n/8 is equal to “floor(n/8) + (n%8)/8”. Let us write the above expression in terms of floor(n/8) and n%8

n/9 = floor(n/8) + (n%8)/8 - [floor(n/8) + (n%8)/8]/9
n/9 = floor(n/8) - [floor(n/8) - 9(n%8)/8 + (n%8)/8]/9
n/9 = floor(n/8) - [floor(n/8) - n%8]/9

From above equation, n is a multiple of 9 only if the expression floor(n/8) – [floor(n/8) – n%8]/9 is an integer. This expression can only be an integer if the sub-expression [floor(n/8) – n%8]/9 is an integer. The subexpression can only be an integer if [floor(n/8) – n%8] is a multiple of 9. So the problem reduces to a smaller value which can be written in terms of bitwise operators.

[ad type=”banner”]