Check if n is divisible by power of 2 without using arithmetic operators
Last Updated :
26 May, 2022
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)
Share your thoughts in the comments
Please Login to comment...