Drill

ProblemsPython › warmup

Steps to reach one

easywarmupPython

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.

collatz_steps(start: int) → int

Solve it in the editor →

Where you start

def collatz_steps(start: int) -> int:
    

Worked examples

CallResult
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

The same problem in another language

More warmup problems in Python