Given two positive integers n and m, check whether n is divisible by 2^m without using arithmetic operators
Examples:
Input: n = 8, m = 2
Output: Yes
Explanation: 2^2=4, and 8 is divisible by 4.Input: n = 14, m = 3
Output: No
Explanation: 2^3=8, and 14 is not divisible by 8.
Using Bitwise Operators - O(1) Time and O(1) Space
The idea of this approach is based on the bitwise properties of powers of 2. A number is divisible by 2 if its least significant bit (LSB) is 0, divisible by 4 if the two least significant bits are 0, divisible by 8 if the three least significant bits are 0, and so on. Using this property, a number n is divisible by 2^m if its last m bits are all 0.
We can check this using the expression: n & ((1 << m) - 1)
Here’s how it works:
- 1 << m shifts the number 1 to the left by m positions, giving 2^m.
- (1 << m) - 1 creates a mask with the last m bits set to 1.
- n & ((1 << m) - 1) extracts the last m bits of n.
- If the result is 0, then n is divisible by 2^m; otherwise, it is not.
using namespace std;
// function to check whether n
// is divisible by pow(2, m)
bool isDivBy2PowerM(unsigned int n, unsigned int m)
{
// if expression results to 0, then
// n is divisible by pow(2, 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;
}
class GFG {
// function to check whether n
// is divisible by pow(2, m)
static boolean isDivBy2PowerM(int n, int m)
{
// if expression results to 0, then
// n is divisible by pow(2, 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");
}
}
# function to check whether n
# is divisible by pow(2, m)
def isDivBy2PowerM(n, m):
# if expression results to 0, then
# n is divisible by pow(2, m)
if (n & ((1 << m) - 1)) == 0:
return True
return False
def main():
n, m = 8, 2
if isDivBy2PowerM(n, m):
print("Yes")
else:
print("No")
if __name__ == "__main__":
main()
using System;
class GFG {
// function to check whether n
// is divisible by pow(2, m)
static bool isDivBy2PowerM(uint n, uint m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if ((n & ((1U << (int)m) - 1)) == 0)
return true;
return false;
}
static void Main()
{
uint n = 8, m = 2;
if (isDivBy2PowerM(n, m))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// function to check whether n
// is divisible by pow(2, m)
function isDivBy2PowerM(n, m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if ((n & ((1 << m) - 1)) === 0)
return true;
return false;
}
// driver code
let n = 8, m = 2;
if (isDivBy2PowerM(n, m))
console.log("Yes");
else
console.log("No");
Output
Yes