![]() |
VOOZH | about |
Given a number n, the task is to check whether this number is a multiple of 4 or not without using +, -, * ,/ and % operators.
Examples :
Input: n = 4 Output - Yes n = 20 Output - Yes n = 19 Output - No
Basic Approach:
Method 1 (Using XOR)
Implementation of the above approach.
0 4 8 12 16 20 24 28 32 36 40
Time Complexity: O(n)
Auxiliary Space: O(1)
How does this work?
When we do XOR of numbers, we get 0 as XOR value just before a multiple of 4. This keeps repeating before every multiple of 4.
Number Binary-Repr XOR-from-1-to-n 1 1 [0001] 2 10 [0011] 3 11 [0000]
Efficient Approach:
Method 2 (Using Bitwise Shift Operators)
Implementation of the above approach.
0 4 8 12 16 20 24 28 32 36 40
Time Complexity: O(1)
Auxiliary Space: O(1)
As we can see that the main idea to find multiplicity of 4 is to check the least two significant bits of the given number. We know that for any even number, the least significant bit is always ZERO (i.e. 0). Similarly, for any number which is multiple of 4 will have least two significant bits as ZERO. And with the same logic, for any number to be multiple of 8, least three significant bits will be ZERO. That's why we can use AND operator (&) as well with other operand as 0x3 to find multiplicity of 4.