VOOZH about

URL: https://www.geeksforgeeks.org/dsa/multiples-4-interesting-method/

⇱ Multiples of 4 (An Interesting Method) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Multiples of 4 (An Interesting Method)

Last Updated : 11 Sep, 2023

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) 

  • If n is equal to 1 return false.
  • Run a loop from 1 to n and find XOR of all numbers.
  • If the result is equal to n, then n is a multiple of 4 else not.

 Implementation of the above approach.


Output
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) 

  • Remove last two bits using >>.
  • Multiply with 4 using <<.
  • If the result is equal to n, then last two bits were 0, hence number is multiple of 4. 
     

Implementation of the above approach.


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

Comment
Article Tags: