Skip to content

Collatz conjecture

Python while + branching

Flowchart (ISO 5807)

YesYesNoNoStartInput nsteps = 0n ≠ 1n mod 2 = 0n = n div 2n = 3n + 1steps = steps + 1Return stepsEndFigure 1 — collatz_steps

Source code

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

The editor opens with this code — change it and the chart redraws.

Language
Python
Constructs
while + branching
Topic
Loops
Formats
Word, Visio, draw.io, PDF, SVG

Related examples