Mihai Stefanescu - 2 years ago 154
Python Question

# Keep on halving by integer division until x=1

The function is to take a positive integer n and divide it by 2 (using integer division) until it reaches 1. The output should be the number of times that value is divided. My code so far is

``````def keep_halving(x):
i=1
for i in range(x):
if x//2==0:
return i
``````

An example of how the function should run is

``````>>>keep_halving(4)
2
``````

You could try this:

``````n = int(input("enter number"))
while n > 1:
n //= 2
print (n)
``````

Input: `128`

Output:

``````enter number128
64
32
16
8
4
2
1
``````

This will continuously divide by two using the `while` loop and stop when `n` gets to one.

``````count = 0
n = int(input("enter number"))
while n > 1:
n //= 2
print (n)
count +=1
print (count)
``````

This will add one onto `count` each time `n` is divided by two.

Input : `128`

Output :

``````enter number128
64
32
16
8
4
2
1
7
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download