In Python, we can easily check if a number is a power of 2 by taking the log base 2 and seeing if the result is a whole number.

import math

def isPowerOfTwo(num):
    if math.log(num,2).is_integer():
        return True
    else:
        return False

print(isPowerOfTwo(2))
print(isPowerOfTwo(12))
print(isPowerOfTwo(32))
print(isPowerOfTwo(94))

#Output:
True
False
True
False

When working with numbers in our programs, sometimes it can be useful to be able to easily check if a number is a power of another number.

In Python, we can check if a number is a power of 2 very easily.

To check if a number is a power of 2, we take the log of that number base 2 and see if the result is a whole number.

To take the log of a number, we use the math module log() function. Then, to see if a number is a whole number, we use the Python float is_integer() function.

Below is the Python code for checking if a number is a power of 2 in Python.

import math

def isPowerOfTwo(num):
    if math.log(num,2).is_integer():
        return True
    else:
        return False

print(isPowerOfTwo(2))
print(isPowerOfTwo(12))
print(isPowerOfTwo(32))
print(isPowerOfTwo(94))

#Output:
True
False
True
False

How to Check if A Number is a Power of Another Number in Python

For the more general case, where you want to check if a number is a power of another number, we can simply adjust our Python function to take another parameter.

Then, in a similar way to above, all we need to do is change the base of the logarithm.

Below is a Python function for you to check if a number is a power of any other number.

import math

def isPower(num1, num2):
    if math.log(num1, num2).is_integer():
        return True
    else:
        return False

print(isPower(2,2))
print(isPower(12,3))
print(isPower(64,4))
print(isPower(81,9))

#Output:
True
False
True
True

Hopefully this article has been useful for you to learn how to check if a number is a power of two in Python.

Categorized in:

Python,

Last Update: February 26, 2024