Collatz sequence with a step limit in JavaScript
Beginner · 4 min read
Pick any whole number. If it is even, halve it. If it is odd, multiply it by 3 and add 1. Do the same to the answer, and keep going. Start from 6 and you get 6, 3, 10, 5, 16, 8, 4, 2, 1. This chain is called the Collatz sequence, and every start anyone has ever tried ends at 1. Nobody has proved that every start does.
In this tutorial you will build the chain, count its steps, find its highest point and search for the longest chain below 1000. Then you will write the version a careful programmer would ship: one with a step limit, because a loop whose ending nobody can prove needs a way out. You need to know while loops, % and the ternary operator ? :.
One step of the rule
The whole rule fits on one line. x % 2 === 0 asks "is x even?", and the ternary picks one of two answers:
const next = (x) => (x % 2 === 0 ? x / 2 : 3 * x + 1);
console.log(next(6), next(3), next(10)); // 3 10 5
condition ? a : b means "if the condition is true, use a, otherwise use b". It is a compact if-else that gives back a value.
Why a step limit matters
A while loop runs until its condition becomes false. If the condition never becomes false, the loop runs forever and the page freezes. For most loops you can see why they end: a counter goes up to a limit, or a list runs out. For the Collatz loop, the only reason to believe it ends is that it always has so far. That is a conjecture, a guess nobody has proved.
Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.
102 The Collatz chain, and what a step cap is for
easyBuild the Collatz sequence for a number: halve it if even, otherwise triple it and add one, until it reaches 1. Report the chain for 6, the step count and peak for 27, and find the longest chain for any start below 1000. Then write the version that gives up after a fixed number of steps and say why.
Stuck? Three hints, smallest first
- 1. One line does the step:
x % 2 === 0 ? x / 2 : 3 * x + 1. - 2. 27 takes far more steps than its size suggests, and rises above 9000 on the way.
- 3. Nobody has proved every chain terminates, so any loop over it needs an escape.
Step 1: build the chain
const collatz = (n) => {
const seq = [n];
let x = n;
while (x !== 1) {
x = x % 2 === 0 ? x / 2 : 3 * x + 1;
seq.push(x);
}
return seq;
};
console.log(collatz(6).join(' ')); // 6 3 10 5 16 8 4 2 1
console.log(collatz(1)); // [ 1 ]
join(' ') prints the chain as one line of numbers. The array starts with n itself, and every new value is pushed on the end. For a start of 1, the condition x !== 1 is false straight away, so the loop never runs and you get [1].
Step 2: count the steps and find the peak
const steps = (n) => collatz(n).length - 1;
const peak = (n) => collatz(n).reduce((m, x) => (x > m ? x : m), 0);
console.log(steps(6), steps(27), peak(27)); // 8 111 9232
console.log(steps(7), peak(7)); // 16 52
The number of steps is one less than the length, because the start isn't a step. The peak is the largest value, found with reduce: keep m if it is bigger, otherwise take x.
27 is the famous one. It is a small number, yet it takes 111 steps and climbs all the way to 9232 before it comes down.
Step 3: powers of two fall straight down
console.log(steps(1), steps(2), steps(1024)); // 0 1 10
1024 is 2 multiplied by itself ten times, so it halves ten times and reaches 1. There is no link between how big the start is and how long the chain is, which is what makes the next step a real search.
Step 4: the longest chain below 1000
const longestUnder = (limit) => {
let bestN = 1;
let bestSteps = -1;
for (let n = 1; n < limit; n++) {
const s = steps(n);
if (s > bestSteps) {
bestSteps = s;
bestN = n;
}
}
return [bestN, bestSteps];
};
console.log(longestUnder(1000)); // [ 871, 178 ]
Keep the best start and its step count so far, and replace both when you find a longer chain. bestSteps starts at -1 so that the very first number always counts as the best so far. 871 wins with 178 steps.
Step 5: the version with a step limit
const reachesOneWithin = (n, cap) => {
let x = n;
let used = 0;
while (x !== 1 && used < cap) {
x = x % 2 === 0 ? x / 2 : 3 * x + 1;
used++;
}
return x === 1;
};
console.log(reachesOneWithin(27, 200), reachesOneWithin(27, 100)); // true false
The loop now has two ways to stop: it reaches 1, or it runs out of steps. After the loop, x === 1 tells you which one happened. 27 needs 111 steps, so a limit of 200 is enough and a limit of 100 isn't.
This costs one counter, and the loop is now guaranteed to end, whatever the conjecture turns out to be.
Step 6: check that the limit really bites
const allTerminate = (limit, cap) => {
for (let n = 1; n <= limit; n++) if (!reachesOneWithin(n, cap)) return false;
return true;
};
console.log(allTerminate(200, 500), allTerminate(200, 50)); // true false
Every start up to 200 finishes within 500 steps, but not within 50. Testing both sides matters. If both came back true, the limit would be decoration that never does anything.
Step 7: why the chain doesn't simply run away
console.log(3 * 27 + 1, (3 * 27 + 1) % 2); // 82 0
An odd number times 3 is odd, and odd plus 1 is even. So every "multiply by 3 and add 1" is followed by at least one halving. That is why the chain keeps coming back down.
The full solution
The answer panel has collatz, steps, peak, longestUnder and the capped reachesOneWithin, and prints every result above, plus 97, which takes 118 steps and reaches the same peak as 27. Press Run to see the output.
const collatz = (n) => {
const seq = [n];
let x = n;
while (x !== 1) {
x = x % 2 === 0 ? x / 2 : 3 * x + 1;
seq.push(x);
}
return seq;
};
const steps = (n) => collatz(n).length - 1;
const peak = (n) => collatz(n).reduce((m, x) => (x > m ? x : m), 0);
// The honest version: bounded, and it reports whether it finished.
const reachesOneWithin = (n, cap) => {
let x = n;
let used = 0;
while (x !== 1 && used < cap) {
x = x % 2 === 0 ? x / 2 : 3 * x + 1;
used++;
}
return x === 1;
};
const allTerminate = (limit, cap) => {
for (let n = 1; n <= limit; n++) if (!reachesOneWithin(n, cap)) return false;
return true;
};
const longestUnder = (limit) => {
let bestN = 1;
let bestSteps = -1;
for (let n = 1; n < limit; n++) {
const s = steps(n);
if (s > bestSteps) {
bestSteps = s;
bestN = n;
}
}
return [bestN, bestSteps];
};
const longest = longestUnder(1000);
console.log('from 6 :', collatz(6));
console.log('from 1 :', collatz(1), '<- the loop never runs');
console.log('27 :', steps(27), 'steps, peaking at', peak(27));
console.log('97 :', steps(97), 'steps, peaking at', peak(97));
console.log('7 :', steps(7), 'steps, peaking at', peak(7));
console.log('powers of two :', steps(1), steps(2), steps(1024));
console.log('longest < 1000:', longest);
console.log('capped at 500 :', allTerminate(200, 500), 'capped at 50:', allTerminate(200, 50));
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 reaches 1 in eight steps', [collatz(6), steps(6)], [[6, 3, 10, 5, 16, 8, 4, 2, 1], 8]);
test('27 is the famous small one: 111 steps and a peak of 9232', [steps(27), peak(27)], [111, 9232]);
test('a power of two falls straight down, one step per bit', [steps(1), steps(2), steps(1024)], [0, 1, 10]);
test('7 takes 16 steps and climbs to 52 first, from a start of 7', [steps(7), peak(7)], [16, 52]);
test('871 has the longest chain below 1000, at 178 steps', longest, [871, 178]);
test('the chain from 1 is just [1], since the loop condition is false at once', collatz(1), [1]);
test('97 reaches the same peak as 27 by a longer road', [steps(97), peak(97)], [118, 9232]);
test('every start up to 200 terminates within 500 steps, and not within 50', [allTerminate(200, 500), allTerminate(200, 50)], [true, false]);
test('3n + 1 on an odd n is always even, so every rise is followed by a fall', [3 * 27 + 1, (3 * 27 + 1) % 2, (3 * 871 + 1) % 2], [82, 0, 0]);
The rule is two lines and the behaviour is wild. 27 takes 111 steps and climbs to 9232 before coming down; 97 takes 118 steps and reaches the same peak. A power of two, by contrast, falls straight to 1 in exactly as many steps as it has bits. There is no relationship between the size of the start and the length of the chain, which is what makes the problem interesting and what makes the search for the longest chain below 1000 a genuine search rather than a formula.
The step cap is the point of the exercise. The Collatz conjecture — that every positive integer reaches 1 — is unproven. So while (x !== 1) is a loop with no proof of termination, and writing it that way in production code means shipping a possible infinite loop on the strength of a conjecture. reachesOneWithin costs one counter and returns a fact you can act on. Asserting that the cap really bites — 200 starts all finish within 500 steps but not within 50 — is what stops the guard being decoration.
One small note on the arithmetic: 3 * n + 1 for odd n is always even, so a rise is always immediately followed by at least one halving. That is why the sequence does not simply run away, and it is the observation every attempted proof starts from. It is also worth knowing that the peak can be far above the start, so a version of this working in 32-bit integers would overflow long before a version working in doubles does.
Common mistakes
- Counting the start as a step. The chain for 6 has nine numbers but only eight steps.
- Shipping
while (x !== 1)with no limit. It works for every number tried so far, but nothing guarantees it, and a frozen page is a bad way to find out. - Passing 0. 0 is even and half of 0 is 0, so
collatz(0)never reaches 1 and never stops. The capped version simply returnsfalse.
Try it yourself
- Print the chain for 97 and find the step where it first goes above 1000.
- Change
reachesOneWithinto return the number of steps used, or-1if it hit the limit. - Find the start below 10000 with the highest peak.