Skip to content
Advertisement

Count how many times can a number be divided by 2

n = int(input())
counter = 0
while n > 0:
   if (n // 2) > 1:
    counter = counter +1
    
print (counter)

Hi, I am a python learner and I am having problems with this homework I was given.

Read a natural number from the input. Find out how many times in a row this number can be divided by two (e.g. 80 -> 40 -> 20 -> 10 -> 5, the answer is 4 times)

And I should use while loop to do it.

Any Ideas, because I really don’t have any idea how to do it. This is my best try

Advertisement

Answer

Your while loop condition is wrong. While the number is evenly divisible by 2, divide it by 2 and increment counter

num = int(input('Enter a number: '))

counter = 0
while num % 2 == 0 and num != 0:
    num = num / 2
    counter = counter + 1

print(counter)
Advertisement