Home > Mobile >  Count how many times can a number be divided by 2
Count how many times can a number be divided by 2

Time:10-15

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

CodePudding user response:

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

while (n % 2) == 0:
    n //= 2
    counter  = 1

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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

if N != 0:
  while 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)
print(0 if (o := b.rfind('1')) < 0 else b[o:].count('0'))
  • Related