+ 1
how to find power of two?
I want to input a positive integer (a)and then want to find if there is an integer( n )like that (a==2**n)
3 ответов
+ 2
This is a question about a logarith with base 2.
I'd recommend to do it this way:
1) check if the integer is a power of two
2)calculate it
the code could be as follows:
====
>>> import math
>>> a = 8 # user input
>>> if not a&(a-1): #check if a is a result of exponentiation of 2
print(int(math.log(a,2))) #if so, find the power
3
>>> # result is 3
+ 1
other than bitwise operations, you can use a while loop and keep dividing the number by 2 and checking the remainder. if the number at any point is not divisible by 2, it isn't a power of 2. (this is slower but a more readable solution for beginners)
+ 1
thanks !