Collatz Conjecture: A Simple yet Elusive Mathematical Problem
The Collatz conjecture (also known as the 3n+1 problem) is one of the most famous unsolved problems in mathematics. It is deceptively simple: take any positive integer n. If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. Repeat. The conjecture states that no matter what starting number you choose, you will always eventually reach the cycle 4, 2, 1. Despite being tested for all numbers up to 2^68 (about 295 quintillion), no one has proven it works for every positive integer.
Implementing the Collatz Sequence in Python
Generating Collatz sequences is a straightforward programming exercise that teaches while loops, conditional logic, and sequence generation. The sequence length (total stopping time) varies dramatically between numbers—some reach 1 in a few steps, while others take hundreds. The maximum value reached (the hailstone peak) can be astronomically larger than the starting number, exceeding 2^100,000 for starting values around 10^9. This unpredictable growth is why the problem is so hard to prove—the sequence can explode far beyond the starting value before eventually descending to 1.
def collatz_sequence(n: int) -> list[int]:
seq = [n]
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
seq.append(n)
return seq
def collatz_stats(n: int) -> dict:
seq = collatz_sequence(n)
return {
"start": n, "steps": len(seq) - 1,
"max_value": max(seq), "max_log10": max(len(str(max(seq))), 1)
}
for start in [7, 27, 97, 871, 6171]:
stats = collatz_stats(start)
print(f"n={stats['start']:>5}: {stats['steps']:>3} steps, "
f"peak={stats['max_value']:>15,} ({stats['max_log10']} digits)")
Visualizing the Sequence
Plotting Collatz sequences reveals the characteristic “hailstone” pattern—sharp rises when odd numbers trigger 3n+1 (which is always even after adding 1), followed by a series of divisions by 2. The sequence often spends most of its time in the descent phase. A logarithmic scale helps visualize both the small values near 1 and the huge peaks at intermediate steps. The 3n+1 operation always produces an even number (since 3n is odd for odd n, 3n+1 is even), so the next step is always a division by 2, preventing consecutive odd operations.
import matplotlib.pyplot as plt
def plot_collatz(start, ax):
seq = collatz_sequence(start)
ax.plot(seq, marker='o', markersize=2, linewidth=0.5)
ax.set_yscale('log')
ax.set_title(f"Collatz: n={start}, steps={len(seq)-1}")
ax.set_xlabel("Step")
ax.set_ylabel("Value (log scale)")
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
for i, n in enumerate([27, 41, 97, 77031]):
plot_collatz(n, axes[i//2, i%2])
plt.tight_layout()
plt.savefig("collatz.png")
Computational Explorations
The conjecture has been verified for all n up to 2^68 using distributed computing (the BOINC-based Collatz Conjecture project). Interesting patterns emerge: numbers of the form 2^k collapse immediately to 1 (no odd steps). Numbers near 2^k often have very long sequences. The longest sequences for a given range follow no obvious pattern—there is no formula to predict the stopping time. The conjecture is related to several other open problems: the existence of a non-trivial cycle (other than 4-2-1), the possibility of a sequence that diverges to infinity, and the density of numbers that reach 1. Mathematicians like Terence Tao have made partial progress (proving that “almost all” Collatz sequences eventually reach a value below the starting point), but a complete proof remains elusive.
# Find the number with the longest sequence in a range
def find_longest(limit: int):
longest = (0, 0, 0) # (n, steps, max_value)
for n in range(1, limit + 1):
stats = collatz_stats(n)
if stats["steps"] > longest[1]:
longest = (n, stats["steps"], stats["max_value"])
return longest
n, steps, peak = find_longest(100000)
print(f"Longest under 100K: n={n}, steps={steps}, peak digits={len(str(peak))}")
The Collatz conjecture’s simplicity combined with its resistance to proof makes it a favorite in recreational mathematics. It teaches that simple rules can produce complex, unpredictable behavior—a theme that appears throughout computer science in cellular automata, chaos theory, and generative art. The conjecture also demonstrates the limits of empirical verification in mathematics: no amount of computational testing can substitute for a proof.
Generalizations and Variants of the Conjecture
Mathematicians have studied several variants of the Collatz conjecture. The 3n+1 problem is one instance of a family of Collatz-like functions. The 5n+1 variant is known to have divergent trajectories (never reaching 1) and additional cycles beyond 4-2-1. The negative Collatz (applied to negative integers) has three known cycles: -1, -2, -1; -5, -14, -7, -20, -10, -5; and a 18-length cycle starting at -17. The generalized Collatz problem (mapping integers based on residue classes modulo p) is formally undecidable—John Conway proved in 1972 that there exist Collatz-like functions for which it is algorithmically impossible to determine whether all inputs eventually reach a cycle.

