Given a number n, check if it is divisible by 17 using bitwise operators.
Input : n = 34 Output : 34 is divisible by 17 Input : n = 43 Output : 43 is not divisible by 17
A naive approach will be to check it by % operator if it leaves a remainder of 0.
To do division using Bitwise operators, we must rewrite the expression in powers of 2.
n/17 = (16*n)/(17*16) = (17 - 1)*n/(17*16) = (n/16) - (n/(17*16))
We can rewrite n/16 as floor(n/16) + (n%16)/16 using general rule of division.
n/17 = floor(n/16) + (n%16)/16 - (floor(n/16) + (n%16)/16)/17 = floor(n/16) - (floor(n/16) - 17*(n%16)/16 + (n%16)/16)/17 = floor(n/16) - (floor(n/16)-n%16)/17
The left-hand-side of this equation is n/17. That will be an integer only when the right-hand-side is an integer. floor(n/16) is an integer by definition. So the whole left-hand-side would be an integer if (floor(n/16)-n%16)/17 is also an integer.
This implies n is divisible by 17 if (floor(n/16)-n%16) is divisible by 17.
(floor(n/16)-n%16) can be written in bitwise as (int)(n>>4) – (int)(n&15) where n>>4 means n/16 and n%15 means n%15
Below is the implementation of the above approach:
35 is not divisible by 17
- Check if a number is divisible by 8 using bitwise operators
- Check if a number is multiple of 9 using bitwise operators
- Check if n is divisible by power of 2 without using arithmetic operators
- Check whether bitwise AND of a number with any subset of an array is zero or not
- Bitwise Operators in C/C++
- Check if a number is positive, negative or zero using bit operators
- Bitwise right shift operators in Java
- What are the differences between bitwise and logical AND operators in C/C++?
- Toggle case of a string using Bitwise Operators
- Russian Peasant (Multiply two numbers using bitwise operators)
- Check if a number is divisible by 41 or not
- Check if a number is divisible by 23 or not
- Check if a large number is divisible by 6 or not
- Check if a large number is divisible by 8 or not
- Check if a large number is divisible by 4 or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Mithun Kumar