Check if n is divisible by power of 2 without using arithmetic operators

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++

// C++ implementation to chech whether n
// is divisible by pow(2, m)
#include <bits/stdc++.h>

using namespace std;

// function to chech 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;

    // n is not divisible
    return false;
}

// Driver program to test above
int main()
{
    unsigned int n = 8, m = 2;
    if (isDivBy2PowerM(n, m))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Python3

# Python3 implementation to chech 
# whether n is divisible by pow(2, m)

# function to chech 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
        
    # n is not divisible
    return False

# Driver program to test above
n = 8
m = 2
if isDivBy2PowerM(n, m):
    print("Yes")
else:
    print( "No")
    
# This code is contributed by "Sharad_Bhardwaj".


Output:

Yes

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.