Predict the output
What does this print?
def halvings(n: int) -> int:
steps = 0
while n > 1:
n //= 2
steps += 1
return steps
print(halvings(1_000), halvings(1_000_000), halvings(10 ** 9))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 9 19 29
Right: about log₂ n halvings in each case.
A thousandfold bigger input adds only about ten steps, which is what logarithmic growth means.
Why not the others?
- B 10 20 30. Integer halving stops when n reaches 1, one step short of the rounded-up logarithm here.
- C 500 500000 500000000. That would be a single halving, not repeated halving.