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

18th Sep 2018, 5:07 PM
sama baluom
sama baluom - avatar
3 Réponses
+ 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
18th Sep 2018, 8:54 PM
strawdog
strawdog - avatar
+ 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)
18th Sep 2018, 9:14 PM
hinanawi
hinanawi - avatar
+ 1
thanks !
19th Sep 2018, 3:46 AM
sama baluom
sama baluom - avatar