Collatz Sequence in Python: Algorithm, Proof Status, and Safe Code

Quick answer: A Collatz implementation repeatedly halves a positive even integer and replaces an odd integer n with 3n + 1. The conjecture that every positive start reaches one is unproved, so production code should validate input, detect repeats, and enforce a step limit.

Python Pool infographic showing a Collatz sequence branching between even halving and odd 3n plus 1 steps until it reaches one
The Collatz iteration halves a positive even number and applies 3n + 1 to an odd number; production code still needs input and step limits.

The Collatz sequence in Python is a simple loop exercise with a surprisingly deep mathematical question behind it. Start with a positive integer. If the number is even, divide it by 2. If the number is odd, multiply it by 3 and add 1. Repeat those two rules until the sequence reaches 1. The same recurrence is also called a hailstone sequence; Hailstone Sequence Python: Collatz Examples and Code adds a companion implementation, trace, and stopping checks.

For example, the start 7 follows 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1. The rule is small enough for a beginner to implement, but the path may rise before it falls. That makes the Collatz problem useful for practicing loops, conditionals, integer division, validation, and tests.

The official Python tutorial on if statements is helpful for the odd and even branches. The numeric types documentation explains integer arithmetic and operators.

Use a while loop for the main solution. The loop condition says exactly what the task needs: keep updating the current number until it becomes 1. Printing inside the loop is fine for a first example, but returning a list or a count is better for reusable code.

Print A Collatz Sequence

The shortest useful version stores the current number, prints it, applies one of the two rules, and stops after the final 1.

n = 7

while n != 1:
    print(n)
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1

print(1)

The modulo check n % 2 == 0 identifies even numbers. The even branch uses // so the result stays an integer. Using normal division would produce floats such as 22.0, which is not the usual form of the sequence.

This version is easy to read, but it only prints output. If you want to test the result, plot it, or compare several starts, return data from a function instead.

Return The Sequence As A List

A list-returning function is the best general-purpose form. It includes the start, every intermediate term, and the final 1.

def collatz_sequence(start):
    if start < 1:
        raise ValueError("start must be positive")

    terms = [start]
    current = start
    while current != 1:
        if current % 2 == 0:
            current = current // 2
        else:
            current = 3 * current + 1
        terms.append(current)

    return terms

print(collatz_sequence(10))

For 10, the function returns [10, 5, 16, 8, 4, 2, 1]. Raising ValueError for zero and negative starts keeps the function aligned with the standard Collatz exercise.

Returning a list also makes testing straightforward. You can compare the whole list for a small start such as 6 or 10, then use counts for larger starts where storing every term is not necessary.

Count Collatz Steps

The stopping time is the number of updates needed to reach 1. It is different from the number of terms because the starting number is a term, not a step.

def collatz_steps(start):
    if start < 1:
        raise ValueError("start must be positive")

    steps = 0
    current = start
    while current != 1:
        if current % 2 == 0:
            current = current // 2
        else:
            current = 3 * current + 1
        steps += 1

    return steps

print(collatz_steps(7))

The start 7 takes 16 steps and has 17 terms when the final 1 is included. This off-by-one detail is one of the most common mistakes in Collatz examples.

Use a step counter when you only need a compact answer. It avoids building a full list and still captures how long the path took.

Python Pool infographic showing Collatz even, odd, halve, triple, and increment steps
Collatz rule: Collatz even, odd, halve, triple, and increment steps.

Validate Text Before Running

User input arrives as text, so convert it before sending it into the sequence function. Keep parsing separate from the Collatz rule so each function has one clear job.

def parse_positive_int(text):
    try:
        number = int(text)
    except ValueError:
        raise ValueError("enter a whole number") from None

    if number < 1:
        raise ValueError("enter a positive number")
    return number

start = parse_positive_int("27")
print(start)
print(start % 2 == 1)

This parser rejects words, blank text, decimal text, zero, and negative numbers. A command-line program can catch the error and print a short message instead of displaying a traceback.

Validation matters because the classic Collatz rule is defined for positive integers. If you allow other input, the output may still be produced by Python, but it no longer represents the normal problem.

Find The Longest Path In A Range

After the step counter works, you can compare several starting numbers. A range scan is a good way to practice loops while keeping the sequence code reusable.

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

best_start = 1
best_steps = 0

for start in range(1, 21):
    steps = collatz_steps(start)
    if steps > best_steps:
        best_start = start
        best_steps = steps

print(best_start, best_steps)

This checks starts from 1 through 20 and reports the start with the largest stopping time in that range. The same pattern can be expanded carefully, but very large searches should include limits and timing checks.

Range scans are useful for learning because they reveal that a larger start does not always mean a longer path. The sequence depends on the odd and even turns taken along the way.

Python Pool infographic showing Collatz start value, terms, stopping condition, and cycle
Sequence: Collatz start value, terms, stopping condition, and cycle.

Use Recursion For A Small Example

A recursive version can express the rule in a compact way, but it is not the best default for large starts. Python protects the interpreter with a recursion limit, and some Collatz paths can be long.

def collatz_recursive(n):
    if n < 1:
        raise ValueError("n must be positive")
    if n == 1:
        return [1]
    if n % 2 == 0:
        return [n] + collatz_recursive(n // 2)
    return [n] + collatz_recursive(3 * n + 1)

print(collatz_recursive(6))

This returns [6, 3, 10, 5, 16, 8, 4, 2, 1]. The base case is n == 1. Without it, the function would call itself until Python raises an error.

Use recursion when the lesson is about function calls and base cases. Use the loop versions when the goal is a practical Collatz implementation.

Common Collatz Mistakes

The first mistake is using / instead of // in the even branch. The second is forgetting to append or print the final 1. The third is counting terms when the question asks for steps. The fourth is accepting invalid input and then wondering why the result does not match examples from textbooks or tutorials.

Good tests should include 1, a short even start such as 6, an odd start such as 7, and invalid starts such as 0 or -3. For returned lists, check the exact terms. For counters, check the stopping time. For parsers, check that bad text raises ValueError.

The Collatz conjecture says every positive integer eventually reaches 1 under these rules, but no proof is known for all positive integers. For Python practice, the important part is smaller: implement the two branches clearly, keep integer arithmetic intact, validate the start, and choose the return shape that matches the task.

Define The Recurrence

For a positive integer n, choose n // 2 when n is even and 3 * n + 1 when it is odd. Keep the recurrence separate from output formatting so it can be tested independently.

Python Pool infographic showing Collatz limits, large values, caching, bounds, and protection
Safe iteration: Collatz limits, large values, caching, bounds, and protection.

Set A Clear Stopping Policy

Stop at one for ordinary exploration, record a repeated value if a cycle appears, and enforce a maximum step count. A limit is important when inputs are untrusted or the conjecture is not being assumed as a proof.

Validate Inputs

Reject booleans, zero, negatives, non-integral values, or values outside the workload’s budget according to the API contract. Python integers avoid fixed-width overflow, but enormous values can still be expensive.

Python Pool infographic checking known Collatz values, steps, claims, and tests
Result checks: Python Pool infographic checking known Collatz values, steps, claims, and tests.

Measure The Sequence

Decide whether the result includes the starting value, the terminal one, the peak value, or only the number of steps. Naming these metrics avoids off-by-one mistakes in comparisons.

Cache Carefully

Memoizing known stopping lengths can accelerate repeated starts, but the cache consumes memory and must not be treated as evidence that every positive integer terminates.

Test Small And Extreme Cases

Test one, even and odd starts, a known long trajectory, invalid inputs, repeated detection, step limits, peak tracking, and the exact output convention. Compare an iterative version with a simple reference implementation.

The Collatz conjecture reference describes the open mathematical problem; the official Python integer documentation explains arbitrary-precision integers. Related Python Pool references include tests and sequence handling.

For related sequence algorithms, compare list construction, step-limit tests, and memoization state before exploring Collatz trajectories.

Frequently Asked Questions

What is the Collatz sequence?

Starting from a positive integer, repeatedly divide even values by two and replace odd values with 3n + 1; the conjecture says every positive start eventually reaches one.

Is the Collatz conjecture proven?

No general proof is known. Code can explore many starting values, but computational evidence is not a proof for all positive integers.

How should I stop a Python implementation?

Stop when the value reaches one, detect a repeated value, and enforce a maximum number of steps so invalid input or unexpected behavior cannot run forever.

Why use arbitrary-precision integers?

Python integers grow automatically, which avoids fixed-width overflow, but large intermediate values can still consume time and memory and should be bounded in untrusted workloads.

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Andy
Andy
4 years ago

This was very very helpful. Thank you, I was breaking my mind with an infinite loop