Steps to reach one
The Collatz rule: halve an even number, or triple an odd one and add one. Count how many steps it takes to land on 1.
- Starting at 1 takes no steps at all.
- A start below 1 is not a valid starting point: return -1.
- Every start given here reaches 1 well inside a 32-bit integer.
collatz_steps(start: int) → int
Where you start
def collatz_steps(start: int) -> int:
Worked examples
| Call | Result |
|---|---|
collatz_steps(1) | 0 |
collatz_steps(6) | 8 |
collatz_steps(7) | 16 |
collatz_steps(27) | 111 |
Hint
A while loop that stops at 1, counting as it goes.
Reference solution in Python
def collatz_steps(start: int) -> int:
if start < 1:
return -1
n, steps = start, 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
return steps