Lamar
Lamar

Reputation: 217

Finding the closest number which is a power of 2 and smaller then the input

So far I have the code posted below. I am basically inputting any number into the function and I should be returned with the number closest to the input which is a power of two, and smaller than the input. Nothing is being printed or outputted.

def pow2(num):
    x=0
    expo = 2**x
    while num > 0:
        x+=1
        if expo >  num:
            print(expo)
            expo = 2 ** (x-1)
            return expo
pow2(55)

Upvotes: 0

Views: 199

Answers (1)

Selcuk
Selcuk

Reputation: 59444

Your while loop is an endless one since num never changes and you only recalculate expo if it is greater than num, which remains False if it was initially False.

A fixed implementation could be:

def pow2(num):
    x = 0
    while 2**(x+1) < num:
        x += 1
    return 2**x

print(pow2(55))

Note that the function only returns a value and does not print it. It is advisable for the functions to only return values and not have side effects such as printing.

Upvotes: 1

Related Questions