Count how many times can a number be divided by 2

Question:

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

Asked By: Proxim17y

||

Answers:

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)
Answered By: Tantary Tauseef

You are not changing n. I would write it like this:

while (n % 2) == 0:
    n //= 2
    counter += 1
Answered By: szachy-a

You need to test whether a number is divisible by 2. You can do this in one of two ways…

x % 2 == 0 # will be True if it's divisible by 2
x & 1 == 0 # will be True if it's divisible by 2

So, you need a loop where you test for divisibility by 2, if True divide your original value by 2 (changing its value) and increment a counter

N = int(input())

counter = 0

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

print(counter)

Or, if you prefer more esoteric programming, then how about this:

N = int(input())
b = bin(N)
o = b.rfind('1')
print(0 if o < 0 else b[o+1:].count('0'))
Answered By: OldBill

Try this, we take the value from "n" and check whether it is divisible by two or not. If it is divisible by two, we increment the counter and then divide that number by 2. If not, it will print the output.

n = int(input("Input your number: "))
counter = 0
while n % 2 != 1:
    counter = counter + 1
    n = n/2
print(counter)
Answered By: Himesh A

The code above will not work as intended. The intended functionality is to take an input natural number and find out how many times in a row the number can be divided by 2. However, the code will only divide the number by 2 once.

To fix this, you can change the code to the following:

n = int(input())
counter = 0
while n > 0:
   if (n % 2) == 0:
    counter = counter +1
    n = n // 2
    
print (counter)
Answered By: LuckyOwl
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.