Editor

Python Program to Print the Collatz Sequence

Beginner · Numbers

The Collatz sequence starts from any positive whole number and repeats one rule: if the number is even, halve it, and if it is odd, multiply it by 3 and add 1. Every starting number ever tried has eventually reached 1, but nobody has proved that all of them do, which makes it one of the most famous unsolved problems in maths.

Program

collatz_sequence.py
num = 6 # or: num = int(input("Enter a positive number: "))
if num < 1:
print("Please enter a positive number")
else:
n = num
sequence = [n]
while n != 1:
if n % 2 == 0:
n = n // 2 # even: halve it
else:
n = 3 * n + 1 # odd: triple it and add 1
sequence.append(n)
print(f"Collatz sequence for {num}:")
print(" -> ".join(str(x) for x in sequence))
print("Steps to reach 1:", len(sequence) - 1)
print("Highest value reached:", max(sequence))
Output
Collatz sequence for 6:
6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Steps to reach 1: 8
Highest value reached: 16

How it works

  1. Numbers below 1 are rejected first, because 0 would halve to 0 for ever and the loop would never end.
  2. n % 2 == 0 tests for an even number, which is halved with // so it stays a whole number.
  3. An odd number becomes 3 * n + 1, and every new value is added to the sequence list.
  4. The loop stops at 1, and the program prints the sequence, the number of steps and the highest value it climbed to.

Other ways to write it

Longest sequence below 100

Longest sequence below 100
def collatz_steps(n):
steps = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
return steps
best = max(range(1, 100), key=collatz_steps)
print("Below 100, the longest sequence starts at", best)
print("It takes", collatz_steps(best), "steps to reach 1")
Output
Below 100, the longest sequence starts at 97
It takes 118 steps to reach 1

max() with key=collatz_steps returns the starting number whose sequence is longest, not the length itself.

Using recursion

Using recursion
def collatz(n):
print(n, end=" ")
if n == 1:
print()
return
collatz(n // 2 if n % 2 == 0 else 3 * n + 1)
collatz(7)
Output
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

The function prints the current number and then calls itself with the next one, stopping when it reaches 1.

Try it yourself

Set num = 27 and see how high the sequence climbs before it falls back to 1.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises