Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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:
    num = num / 2
    counter = counter + 1

print(counter)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading