Check if a number is multiple of 9 using bitwise operators

  • 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.

 

 

 Code Explanation 

  • Here we pass number 18 as a function argument, which is multiple of 9.
  • When first time function call occur, it checks for first two condition which becomes false, then it goes to return statement which work like follow

 

  •  Now return statement’s return value is zero(‘0’),
  • And second time recursive call occur which returns true, means number is multiple of 9.  

Suggested Reading

  1. Write a Macro’s Set,clear and toggle n’th bit using bit wise operators?
  2. Write a c program to implement XOR functionality with out using XOR(^) operator
  3. How to turn off a particular bit in a number?

If you like this Article, then don’t forget to Click on Social likes buttons.