How do I decompose a number into powers of 2?

后端 未结 8 1331
旧巷少年郎
旧巷少年郎 2020-12-20 16:45

I\'m trying to create a function that receives a number as an argument and performs actions on that number to find out its closest powers of 2 that will then add up to that

相关标签:
8条回答
  • 2020-12-20 17:34

    Rather than solve the problem, how about some information to help you solve it? Take a look at a few examples, and solve them. Here are a few,

    Suppose N=2, then the answer is = {2=2^1}.

    Suppose N=3, then the answer is = {2=2^1,1=2^0} (note that 2**0=1)

    Suppose N=4, then the answer is = {4=2^2}

    ...

    Suppose N=63, then the answer is = {32=2^5, 16=2^4, 8=2^3, 4=2^2, 2=2^1, 1=2^0}

    Suppose N=64, then the answer is = {64=2^6}

    ...

    Suppose N=259, then the answer is = {256=2^8, 2=2^1, 1=2^0}

    Do you see the pattern?


    Want an algorithm?

    Think about these simple steps, and combine them together in a loop,

    Can you check if the number is odd? When the number is odd, then you have detected a bit 'on'. Subtract one (make the number even).

    Can you divide by 2? What do you do with the result?

    0 讨论(0)
  • 2020-12-20 17:43

    The best and fastest way to do this is, of course, with binary numbers, but here's a way with a generator:

    def powers_finder(num):
        d = []
        while sum(d) < num:
            p = powers_of_2()
            a=b=1
            while sum(d)+a<=num:
                b=a
                a = next(p)
            d.append(b)
        d.reverse()
        return d
    
    def powers_of_2():
        n=1
        while 1:
            yield n
            n*=2
    

    >>> print(powers_finder(5))
    [1, 4]
    >>> print(powers_finder(8))
    [8]
    >>> print(powers_finder(9))
    [1, 8]
    >>> print(powers_finder(14))
    [2, 4, 8]
    
    0 讨论(0)
提交回复
热议问题