- To check the given number is power of 2, simply take the log of the number on base 2 and if you get an integer then number is power of 2.
- To get the log of the number on base 2 use the module math and use log2() function, the log2() function returns the float value.
- To get the integer value just compare the ceil and floor value of the float value. If the ceil and floor value is equal, then it must be a integer.
Program :
# Program to check the given number is power of 2
import math
def isPowerOfTwo(num):
return math.ceil(math.log2(num)) == math.floor(math.log2(num))
num = int(input("Enter number: "))
if (isPowerOfTwo(num)):
print(f"{num} is a power of 2");
else:
print(f"{num} is not a power of 2");
Output :
Comments