Efficiently check whether n is a multiple of 4 or not
Given a number n. The problem is to efficiently check whether n is a multiple of 4 or not without using arithmetic operators.
Examples:
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.
C++
#include <bits/stdc++.h>
using namespace std;
string isAMultipleOf4( int n)
{
if ((n & 3) == 0)
return "Yes" ;
return "No" ;
}
int main()
{
int n = 16;
cout << isAMultipleOf4(n);
return 0;
}
|
Java
class GFG {
static boolean isAMultipleOf4( int n)
{
if ((n & 3 ) == 0 )
return true ;
return false ;
}
public static void main(String[] args)
{
int n = 16 ;
System.out.println(isAMultipleOf4(n) ? "Yes" : "No" );
}
}
|
Python 3
def isAMultipleOf4(n):
if ((n & 3 ) = = 0 ):
return "Yes"
return "No"
if __name__ = = "__main__" :
n = 16
print (isAMultipleOf4(n))
|
C#
using System;
class GFG {
static bool isAMultipleOf4( int n)
{
if ((n & 3) == 0)
return true ;
return false ;
}
public static void Main()
{
int n = 16;
Console.WriteLine(isAMultipleOf4(n) ? "Yes" : "No" );
}
}
|
PHP
<?php
function isAMultipleOf4( $n )
{
if (( $n & 3) == 0)
return "Yes" ;
return "No" ;
}
$n = 16;
echo isAMultipleOf4( $n );
?>
|
Javascript
<script>
function isAMultipleOf4(n)
{
if ((n & 3) == 0)
return true ;
return false ;
}
let n = 16;
document.write(isAMultipleOf4(n) ? "Yes" : "No" );
</script>
|
Output:
Yes
Time Complexity : O(1)
Auxiliary Space: O(1)
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) == 0)
n is a multiple of x
Else
n is NOT a multiple of x
Last Updated :
15 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...