Collatz sequence in JavaScript
Intermediate · 4 min read
Here is a game with numbers. Pick any whole number. If it's even, halve it. If it's odd, multiply it by 3 and add 1. Repeat. Start at 6 and you get 6, 3, 10, 5, 16, 8, 4, 2, 1. That chain is called the Collatz sequence, and it's a favorite puzzle because nobody has proved that every starting number ends at 1.
In this tutorial you will write collatz(start), which follows the chain, counts the steps to reach 1, and records the highest number on the way. Then you'll find which start below 30 takes the longest, and add a safety limit so the loop always stops. You need to know while loops, % and arrays.
The rule in code
"Even" means it divides by 2 with nothing left over, so n % 2 === 0. The ternary operator, condition ? a : b, picks between two values in one line:
const next = (n) => (n % 2 === 0 ? n / 2 : 3 * n + 1);
console.log(next(6)); // 3: even, so halve it
console.log(next(3)); // 10: odd, so 3 * 3 + 1
console.log(next(10)); // 5
Why the loop needs a guard
A while loop runs until its condition becomes false. A loop written while (n !== 1) only stops if the chain really reaches 1. Mathematicians have checked enormous numbers of starts and every one reached 1, but nobody has proved it must. So we give the loop a cap, a maximum number of steps, and say whether we hit it.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
149 The Collatz chain, and why it needs a guard
fairStart at a number. If it is even, halve it; if it is odd, treble it and add one. Count how many steps it takes to reach 1, record the highest number reached on the way, and find which start below 30 takes the longest. Put a cap on the loop and say why it is there.
Stuck? Three hints, smallest first
- 1. One
whileloop, one branch onn % 2. - 2. Track the peak as you go, because it can go far above where you started.
- 3. Nobody has proved every start reaches 1, so the loop needs a way out.
Step 1: follow the chain and count the steps
function collatz(start) {
let n = start;
let steps = 0;
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
steps++;
}
return steps;
}
console.log(collatz(6)); // 8
console.log(collatz(1)); // 0
Each pass through the loop works out the next number and adds one to steps. From 6 there are eight moves to reach 1. Starting at 1, the loop never runs, so it takes 0 steps.
Step 2: record the path and the peak
Now keep every number in an array called path, and remember the highest one, the peak:
function collatz(start) {
let n = start;
let steps = 0;
let peak = start;
const path = [start];
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
if (n > peak) peak = n;
path.push(n);
steps++;
}
return { steps, peak, path };
}
console.log(collatz(6).path.join(' -> ')); // 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
console.log(collatz(6).path.length); // 9
console.log(collatz(7).steps, collatz(7).peak); // 16 52
The path from 6 has nine numbers but only eight steps, because the starting number isn't a step. Count the arrows, not the numbers.
Look at 7: it climbs all the way to 52 before coming down. The chain doesn't fall steadily, which is why the peak is worth tracking.
Step 3: the start that never stops
Try 0. It's even, so we halve it, and half of 0 is 0. The chain is 0, 0, 0 for ever, and while (n !== 1) would never finish. You don't need an unsolved puzzle to get stuck: one unexpected input is enough.
So add a cap parameter with a default of 500, stop when steps reaches it, and report whether that happened:
function collatz(start, cap = 500) {
let n = start;
let steps = 0;
let peak = start;
const path = [start];
while (n !== 1 && steps < cap) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
if (n > peak) peak = n;
path.push(n);
steps++;
}
return { steps, peak, capped: n !== 1, path };
}
console.log(collatz(0, 20).capped); // true
console.log(collatz(0, 20).path[20]); // 0
console.log(collatz(27, 5).steps, collatz(27, 5).capped); // 5 true
console.log(collatz(27).capped); // false
capped is true when the loop stopped without reaching 1. That flag is important. Without it, collatz(27, 5) would return 5 steps and look like a real answer. With it, the result says "I gave up after 5", which is the honest answer.
Step 4: find the longest chain under 30
Loop over every start from 1 to 30 and keep the one with the most steps:
function collatz(start, cap = 500) {
let n = start;
let steps = 0;
let peak = start;
const path = [start];
while (n !== 1 && steps < cap) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
if (n > peak) peak = n;
path.push(n);
steps++;
}
return { steps, peak, capped: n !== 1, path };
}
let longest = 1;
for (let start = 1; start <= 30; start++) {
if (collatz(start).steps > collatz(longest).steps) longest = start;
}
console.log(longest); // 27
console.log(collatz(27).steps); // 111
console.log(collatz(27).peak); // 9232
console.log(collatz(16).path.join(' -> ')); // 16 -> 8 -> 4 -> 2 -> 1
27 is the winner by a long way: 111 steps, climbing to 9232, more than 300 times where it started. Compare 16, a power of two, which only ever halves.
This loop calls collatz(longest) again every time it compares. That's fine for 30 starts. For thousands, you'd save each result instead of working it out twice.
The full solution
The answer panel has collatz with its cap, finds the longest start up to 30, and prints the chain from 6. The checks cover the chain from 6, the step count, the start of 1, the climb from 7, the record from 27, a power of two, the cap and the start of 0. Press Run to see the output.
function collatz(start, cap = 500) {
let n = start;
let steps = 0;
let peak = start;
const path = [start];
while (n !== 1 && steps < cap) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
if (n > peak) peak = n;
path.push(n);
steps++;
}
return { steps, peak, capped: n !== 1, path };
}
let longest = 1;
for (let start = 1; start <= 30; start++) {
if (collatz(start).steps > collatz(longest).steps) longest = start;
}
console.log('from 6:', collatz(6).path.join(' -> '));
console.log('longest start under 30 is', longest, 'at', collatz(longest).steps, 'steps, peaking at', collatz(longest).peak);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the chain from 6', collatz(6).path, [6, 3, 10, 5, 16, 8, 4, 2, 1]);
test('which is eight steps, one fewer than the numbers listed', [collatz(6).steps, collatz(6).path.length], [8, 9]);
test('one is already there', [collatz(1).steps, collatz(1).path], [0, [1]]);
test('a small odd start wanders a long way up first', [collatz(7).steps, collatz(7).peak], [16, 52]);
test('27 is the worst start under thirty by a distance', [longest, collatz(27).steps, collatz(30).steps], [27, 111, 18]);
test('and it climbs to 9232, over three hundred times where it began', [collatz(27).peak, Math.floor(collatz(27).peak / 27)], [9232, 341]);
test('a powers-of-two start is the easy case: nothing but halving', collatz(16).path, [16, 8, 4, 2, 1]);
test('the cap stops it early rather than lying about the answer', [collatz(27, 5).steps, collatz(27, 5).capped, collatz(27).capped], [5, true, false]);
test('and zero never terminates, which is exactly what the cap is for', [collatz(0, 20).capped, collatz(0, 20).path[20]], [true, 0]);
The loop is four lines and the interesting part is the shape of the numbers. A chain does not descend steadily: from 7 it climbs to 52 before coming down, and from 27 it reaches 9232 — more than three hundred times its start — after 111 steps. That is why peak is tracked separately. Anything that allocated an array sized by the starting number would be badly wrong.
The cap is not defensive padding, it is intellectual honesty. The Collatz conjecture — that every positive integer reaches 1 — has been checked past 268 and never proved, so a loop written as while (n !== 1) is a loop whose termination nobody can guarantee. And you do not need an unproven conjecture to hit it: start at 0 and the sequence is 0, 0, 0 for ever, which the last assertion shows. Returning a capped flag rather than a wrong number is the difference between "no answer yet" and "the answer is 5".
Two practical notes. 3 * n + 1 grows fast, so a large start can pass Number.MAX_SAFE_INTEGER and the halving stops being exact — BigInt is the fix if you are exploring seriously. And repeated calls like collatz(start).steps > collatz(longest).steps recompute whole chains; that is fine for thirty starts and would need memoising for thirty thousand, since every chain ends up walking the tail of a shorter one.
Common mistakes
- Counting the numbers instead of the steps. The chain from 6 has nine numbers and eight steps.
- Writing
while (n !== 1)with no cap. A start of 0 never ends, and nobody can promise every other start does. - Returning a step count without saying it was capped. "Stopped after 500" and "took 500 steps" need to look different.
Try it yourself
- Find the longest chain for starts from 1 to 1000. Which start wins, and how many steps does it take?
- Make
collatzreturn early withcapped: trueifnis not a positive whole number. - Print the peak for every start from 1 to 30. Which ones peak at 9232?