Given two positive integers n and m. The problem is to check whether n is divisible by 2m or not without using arithmetic operators.
Examples:
Input : n = 8, m = 2
Output : Yes
Input : n = 14, m = 3
Output : No
Approach: If a number is divisible by 2 then it has its least significant bit (LSB) set to 0, if divisible by 4 then two LSB’s set to 0, if by 8 then three LSB’s set to 0, and so on. Keeping this in mind, a number n is divisible by 2m if (n & ((1 << m) – 1)) is equal to 0 else not.
C++
#include <bits/stdc++.h>
using namespace std;
bool isDivBy2PowerM(unsigned int n,
unsigned int m)
{
if ((n & ((1 << m) - 1)) == 0)
return true ;
return false ;
}
int main()
{
unsigned int n = 8, m = 2;
if (isDivBy2PowerM(n, m))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean isDivBy2PowerM( int n,
int m)
{
if ((n & (( 1 << m) - 1 )) == 0 )
return true ;
return false ;
}
public static void main(String[] args)
{
int n = 8 , m = 2 ;
if (isDivBy2PowerM(n, m))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isDivBy2PowerM (n, m):
if (n & (( 1 << m) - 1 )) = = 0 :
return True
return False
n = 8
m = 2
if isDivBy2PowerM(n, m):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isDivBy2PowerM( int n, int m)
{
if ((n & ((1 << m) - 1)) == 0)
return true ;
return false ;
}
public static void Main()
{
int n = 8, m = 2;
if (isDivBy2PowerM(n, m))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
PHP
<?php
function isDivBy2PowerM( $n , $m )
{
if (( $n & ((1 << $m ) - 1)) == 0)
return true;
return false;
}
$n = 8;
$m = 2;
if (isDivBy2PowerM( $n , $m ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isDivBy2PowerM(n, m)
{
if ((n & ((1 << m) - 1)) == 0)
return true ;
return false ;
}
let n = 8, m = 2;
if (isDivBy2PowerM(n, m))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output:
Yes
Time Complexity : O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
26 May, 2022
Like Article
Save Article