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 for 6: 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 Steps to reach 1: 8 Highest value reached: 16
How it works
- Numbers below 1 are rejected first, because 0 would halve to 0 for ever and the loop would never end.
n % 2 == 0tests for an even number, which is halved with//so it stays a whole number.- An odd number becomes
3 * n + 1, and every new value is added to thesequencelist. - 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises