Python program to check the given number is the power of 2 or not
In this tutorial, we will learn how to check the given number is the power of 2 or not in python programming. A positive number N is given by the user and we have to check whether it is equal to 2^x or not where x may be zero or any positive number. We will use a simple method to solve this problem, we simply take the log of the number base 2 and if you get an integer then the number is the power of 2. Before going to solve the absolute problem we will learn to find the log of any positive number N base M.
How to find the log of any positive number N base M in Python
Here, the user gives us the value of N and M which are 23458 and 3 respectively. To find the log value of positive number N, we will import the math module in the program. Now we will simply calculate the log of N base M.
N=23458 M=3 from math import log s=log(N,M) p=round(s,2) print('log of N base M:') print(p)
The round function uses to get the value of s to two decimal places.
log of N base M: 9.16
How to check the given number is the power of 2 or not in Python
let’s assume the value of N given by the user is 241565.
N=241565 M=2 from math import log s=log(N,M) if int(s)==s: print('Power of 2') else: print('Not power of 2')
Not power of 2
Similarly, we can also check the number is the power of another number by replacing the value of M.
So Guy’s, I hope you find it useful.
You may also read: