Mihai Stefanescu - 1 year ago 108

Python Question

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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.

Edit: I read your question too fast. Here is updated code:

```
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**