Robert Eisele
Engineer, Systems Architect and DBA

Project Euler 14: Longest Collatz sequence

Problem 14

The following iterative sequence is defined for the set of positive integers:

nn/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

Solution

The Collatz Chain must be seen as quite unpredictable, since it's not proven to always converge to 1. As such, we have no chance to reduce the search space und must observe every number under one million.

function length(n) {

  for (var c = 1; n > 1; c++) {

    if (n % 2 === 0)
      n/= 2;
    else
      n = 3 * n + 1;
  }
  return c;
}

function solution(n) {

  var max = 0, max_i = 0;

  for (var i = 1; i < n; i++) {

    var c = length(i);
    if (c > max) {
      max = c;
      max_i = i;
    }
  }
  return max_i;
}

What we can do however is to define the length function to work recursively and use memorization to reduce the cost of the Collatz Chain calculation:

var H = {1: 1};

function length(n) {

  if (H[n] === undefined) {
    H[n] = 1 + length(n % 2 ? 3 * n + 1 : n / 2);
  }
  return H[n];
}

As most steps are highly redundant, this approach reduces the number of iterations to a whopping 2.4%. However, the hashmap contains 2,168,610 elements. I keep it like this for now, but an additional parameter counting the iterations could be used to limit the max cache depth to balance between memory and CPU consumption.

« Back to problem overview