← All examples

Collatz conjecture

Python Loops

while + branching

Flowchart (ISO 5807)

YesYesNoNoStartInput nsteps = 0n != 1n % 2 == 0n //= 2n = 3 * n + 1steps += 1Return stepsEndFigure 1 — collatz_steps

Source code

def collatz_steps(n):
    steps = 0
    while n != 1:
        if n % 2 == 0:
            n //= 2
        else:
            n = 3 * n + 1
        steps += 1
    return steps