Emmanuel Akinfulubi

JavaScriptMath

Collatz sequence length in JavaScript

Advanced · 4 min read

Pick any positive whole number. If it is even, halve it. If it is odd, multiply it by 3 and add 1. Repeat. Start from 6 and you get 6, 3, 10, 5, 16, 8, 4, 2, 1. This is the Collatz sequence, and every starting number anyone has ever tried ends at 1. Nobody has proved that it always does. It is one of the most famous unsolved problems in math, built from a rule a child can follow.

In this tutorial you will count how many terms the sequence has for a given start, find the starting number below 1000 with the longest chain, and then add a cache so you can search up to 10000 quickly. You need to know while loops, the % operator and the basics of a Map.

The ternary operator

The rule has two cases, and JavaScript has a compact way to write a choice between two values: condition ? valueIfTrue : valueIfFalse.

JavaScript

const n = 6;
console.log(n % 2 === 0 ? n / 2 : 3 * n + 1); // 3

n % 2 === 0 asks "is n even?". If yes, the result is n / 2. Otherwise it is 3 * n + 1.

Terms or steps?

From 6, the sequence has 9 terms (the numbers in the list) but only 8 steps (the moves between them). Different books and websites count differently. This lesson counts terms, including both the starting number and the final 1. When your answer differs from a table online by exactly one, this is usually why.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

53 Collatz sequence length

hard

Count the terms in the Collatz sequence for n: halve it when even, triple and add one when odd, until it reaches 1. Find the longest chain starting below 1000, then use a cache to reach 10000.

Stuck? Three hints, smallest first
  1. 1. Count terms including both the start and the final 1, and say which you meant.
  2. 2. Chains overlap heavily, so a Map from value to remaining length pays for itself.
  3. 3. The chain for 27 goes far above 27 before coming down, so a cache keyed by value ends up larger than the range you scanned.

Step 1: build the sequence

Step 1

const sequence = (n) => {
  const out = [n];
  while (out.at(-1) !== 1) {
    const last = out.at(-1);
    out.push(last % 2 === 0 ? last / 2 : 3 * last + 1);
  }
  return out;
};
console.log(sequence(6).join(', ')); // 6, 3, 10, 5, 16, 8, 4, 2, 1

out.at(-1) is the last item in the array. We keep applying the rule to it until it is 1. Seeing the whole sequence is great for checking, but you often only need its length.

Step 2: count the terms without storing them

Step 2

function terms(n) {
  let count = 1; // the starting value is a term
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    count++;
  }
  return count;
}
console.log(terms(1), terms(2), terms(6)); // 1 2 9
console.log([1, 2, 4, 8, 1024].map(terms)); // [ 1, 2, 3, 4, 11 ]

count starts at 1, so the start itself is counted. A power of two only ever halves, so 1024 (2 to the 10th) takes 11 terms.

Step 3: 27 goes up before it comes down

Step 3

const peak = (n) => {
  let highest = n;
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    if (n > highest) highest = n;
  }
  return highest;
};
console.log(terms(27));              // 112
console.log(sequence(27).length - 1); // 111
console.log(peak(27));               // 9232

27 takes 112 terms, which is 111 steps. On the way, it climbs to 9232, more than 300 times where it started. That climbing is exactly why the problem is hard: you can't tell in advance how high a sequence will go or how long it will take.

Step 4: the longest chain below 1000

Step 4

let bestBelow1000 = { n: 1, terms: 1 };
for (let n = 1; n < 1000; n++) {
  const t = terms(n);
  if (t > bestBelow1000.terms) bestBelow1000 = { n, terms: t };
}
console.log(bestBelow1000); // { n: 871, terms: 179 }

This tries every start and keeps the best one. { n, terms: t } is shorthand for { n: n, terms: t }. 871 has the longest chain, with 179 terms.

Step 5: share the work with a cache

Chains overlap a lot. The chain from 12 goes to 6, and from there it is exactly the chain from 6. If you have already measured 6, there is no need to walk it again.

The cache is a Map from a number to its term count. To measure n, walk forward until you hit a number already in the cache, remembering the path. Then walk back along the path, filling in each number's count:

Step 5

const cache = new Map([[1, 1]]);
function cachedTerms(n) {
  const path = [];
  let m = n;
  while (!cache.has(m)) {
    path.push(m);
    m = m % 2 === 0 ? m / 2 : 3 * m + 1;
  }
  let length = cache.get(m);
  while (path.length) cache.set(path.pop(), ++length);
  return cache.get(n);
}
console.log(cachedTerms(6));  // 9
console.log(cachedTerms(12)); // 10

For 12, the walk stops after one move, at 6, which is already cached with 9 terms. path.pop() takes the last number off the path (12), and ++length makes it 10. Only one new number was measured.

Step 6: search up to 10000

Step 6

let bestTo10000 = { n: 1, terms: 1 };
for (let n = 1; n <= 10000; n++) {
  const t = cachedTerms(n);
  if (t > bestTo10000.terms) bestTo10000 = { n, terms: t };
}
console.log(bestTo10000); // { n: 6171, terms: 262 }
console.log([1, 6, 27, 871, 9999].every((n) => cachedTerms(n) === terms(n))); // true
console.log(cache.size); // 21664

6171 has the longest chain up to 10000, with 262 terms, and the cached and plain versions agree. Look at the cache size: 21664 entries after scanning only 10000 starts. That is because sequences climb above their start, like 27 reaching 9232, and every number they pass through gets cached too.

The two-loop design is deliberate. A recursive version that caches on the way back would also work, but a long chain means a deep pile of unfinished function calls, which can run out of stack space. The loops have no such limit.

The full solution

The answer panel has terms, sequence, peak and cachedTerms, then prints the sequence for 6, the 27 case, the longest chain below 1000, the longest up to 10000 and the cache size. Press Run to see the output.

The answer

function terms(n) {
  let count = 1;                       // the starting value is a term
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    count++;
  }
  return count;
}

const sequence = (n) => {
  const out = [n];
  while (out.at(-1) !== 1) {
    const last = out.at(-1);
    out.push(last % 2 === 0 ? last / 2 : 3 * last + 1);
  }
  return out;
};

const peak = (n) => {
  let highest = n;
  while (n !== 1) {
    n = n % 2 === 0 ? n / 2 : 3 * n + 1;
    if (n > highest) highest = n;
  }
  return highest;
};

// Cached: walk up to a known value, then fill in the path on the way back.
const cache = new Map([[1, 1]]);
function cachedTerms(n) {
  const path = [];
  let m = n;
  while (!cache.has(m)) {
    path.push(m);
    m = m % 2 === 0 ? m / 2 : 3 * m + 1;
  }
  let length = cache.get(m);
  while (path.length) cache.set(path.pop(), ++length);
  return cache.get(n);
}

let bestBelow1000 = { n: 1, terms: 1 };
for (let n = 1; n < 1000; n++) {
  const t = terms(n);
  if (t > bestBelow1000.terms) bestBelow1000 = { n, terms: t };
}

let bestTo10000 = { n: 1, terms: 1 };
for (let n = 1; n <= 10000; n++) {
  const t = cachedTerms(n);
  if (t > bestTo10000.terms) bestTo10000 = { n, terms: t };
}

console.log('sequence for 6 :', sequence(6));
console.log('terms for 27   :', terms(27), 'peaking at', peak(27));
console.log('longest < 1000 :', bestBelow1000);
console.log('longest <= 1e4 :', bestTo10000);
console.log('cache entries  :', cache.size, 'for a range of 10000');

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.

9 checks

test('1 is a sequence of one term, and 2 of two', [terms(1), terms(2)], [1, 2]);
test('the sequence for 6', sequence(6), [6, 3, 10, 5, 16, 8, 4, 2, 1]);
test('27 takes 112 terms, which is 111 steps', [terms(27), sequence(27).length - 1], [112, 111]);
test('and climbs to 9232 on the way, 341 times its start', peak(27), 9232);
test('a power of two just halves, so 2 ** k takes k + 1 terms', [1, 2, 4, 8, 1024].map(terms), [1, 2, 3, 4, 11]);
test('the longest chain starting below 1000 belongs to 871', [bestBelow1000.n, bestBelow1000.terms], [871, 179]);
test('and up to 10000 it is 6171, with 262 terms', [bestTo10000.n, bestTo10000.terms], [6171, 262]);
test('the cached version agrees with the plain one', [1, 6, 27, 871, 9999].every((n) => cachedTerms(n) === terms(n)), true);
test('and its cache holds more values than the range scanned', cache.size > 10000, true);

Two things make this exercise more than a loop. The first is what you count: 27 has 112 terms and 111 steps, and published tables use both conventions, so a mismatch here is usually a definition disagreement rather than a bug. The second is that the sequence goes up. 27 reaches 9232 before it comes down, which is why the cache ends up with more than 10000 entries after scanning 10000 numbers, and why nobody has proved the process terminates for every input.

The cache is worth the two loops it takes. Chains merge quickly — every even number's chain is one step from n / 2's — so the walk up almost always meets a known value after a few steps, and the walk back fills in the path. Building it the obvious way, by recursing and memoising on the way out, risks a deep stack for a starting value whose chain climbs a long way.

Common mistakes

  • Mixing up terms and steps. 27 has 112 terms and 111 steps. Say which one you count.
  • Assuming the numbers stay small. 27 reaches 9232, so a cache or array sized to your range isn't big enough.
  • Starting count at 0. Then you are counting steps, not terms, and every answer is one lower.

Try it yourself

  1. Change terms to count steps instead, and check that 27 gives 111.
  2. Find the start below 1000 with the highest peak.
  3. Add a step limit to terms so it returns null if a sequence takes more than 1000 steps.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.