Given a number n. The problem is to efficiently check whether n is a multiple of 4 or not without using arithmetic operators.
Input : 16 Output : Yes Input : 14 Output : No
Approach: A multiple of 4 always has 00 as its last two digits in its binary representation. We have to check whether the last two digits of n are unset or not.
How to check whether the last two bits are unset or not.
If n & 3 == 0, then the last two bits are unset, else either both or one of them are set.
Can we generalize above solution?
Similarly we can check for other powers of 2. For example, a number n would be multiple of 8 if n & 7 is 0. In general we can say.
// x must be a power of 2 for below // logic to work if (n & (x -1) == n) n is a multiple of x Else n is NOT a multiple of x
This article is contributed by Ayush Jauhri. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Efficiently check if a string has all unique characters without using any additional data structure
- Check if binary string multiple of 3 using DFA
- Check whether a very large number of the given form is a multiple of 3.
- Check if a number is multiple of 9 using bitwise operators
- Write an Efficient Method to Check if a Number is Multiple of 3
- Finding the Parity of a number Efficiently
- Program to invert bits of a number Efficiently
- Efficiently find first repeated character in a string without using any additional data structure in one traversal
- Round to next smaller multiple of 8
- Round to next greater multiple of 8
- Find the multiple of x which is closest to a^b
- Find the largest multiple of 2, 3 and 5
- Find the largest multiple of 3 | Set 1 (Using Queue)
- Smallest multiple of 3 which consists of three given non-zero digits
- Find the largest multiple of 3 from array of digits | Set 2 (In O(n) time and O(1) space)