How to return a list of numbers of the power of 2?

后端 未结 5 2021
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 10:56
def problem(n):
myList = []
for j in range(0, n):
    number = 2 ** j
    myList.append(number)
return myList

I want this code to return the powers

5条回答
  •  逝去的感伤
    2021-01-19 11:23

    import math
    n = input()
    a = [i for i in xrange(2, n+1) if (math.log(i)/math.log(2)).is_integer()]
    print a
    >>> [2, 4, 8, 16 ...]
    

    Returns list of powers of 2 less than or equal to n

    Explanation:
    A number can only be a power of 2 if its log divided by the log of 2 is an integer.

    eg. log(32) = log(2^5) = 5 * log(2)
    5 * log(2) when divided by log(2) gives 5 which is an integer.

    Also there will be floor(math.log(n, 2)) elements in the list, as that is the formula for the number of powers of 2 below n if n itself is not a power of 2

提交回复
热议问题