0

What is the most optimized way to find the power of 2 of a number. For example : if number is 64 then I want 6 as result.

P.S. : I have read many posts about how to check if the number can be represented as a power of 2 or not but they don't give the actual power as result.

Anudocs
  • 686
  • 1
  • 13
  • 54

4 Answers4

3

The two logarithm of a number is the power it'd have to have to be that number:

>>> import math
>>> math.log2(64)
6.0
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
3

It's kind of hack. Convert it to binary number. If input is going to be a multiple of 2, then this would not be a problem

>> bin(2).count('0') -1
1
>>> bin(64).count('0') -1
6
>>> bin(1024).count('0') -1
10
>>> bin(1024)
'0b10000000000'
sam
  • 1,819
  • 1
  • 18
  • 30
1

You just need to compute the logarithm of the number in base 2. Following are the two ways to do so

Method 1

import numpy as np

number = 64

power = np.log2(64)
# 6.0

Method 2

import math

math.log2(number)
# 6.0
Sheldore
  • 37,862
  • 7
  • 57
  • 71
1

this is an option (you are looking for the logarithm in base 2):

from math import log2


def integer_log2(n):
    if not bin(n).count("1") == 1:
        raise ValueError
    return int(log2(n))

in binary representation (bin(n)) a number an only be an integer power o 2 it it contains exactly one 1. the function presented here will raise a ValueError if this is not the case.

integer_log2(64))
# 6

as you'd need the binary representation anyway, you could then also just count the number of 0s to get the log:

def integer_log2(n):
    b = bin(n)
    if not b.count("1") == 1:
        raise ValueError
    return b.count("0") - 1
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111