JavaScript Implementation of Problem 14

View source code here on GitHub!

p0014()

Project Euler Problem 14

This was pleasantly easy to adapt from my Python solution.

Problem:

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

n → n/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.

Returns:

number --

 1/**
 2 * Project Euler Problem 14
 3 *
 4 * This was pleasantly easy to adapt from my Python solution.
 5 *
 6 * Problem:
 7 *
 8 * The following iterative sequence is defined for the set of positive integers:
 9 *
10 * n → n/2 (n is even)
11 * n → 3n + 1 (n is odd)
12 *
13 * Using the rule above and starting with 13, we generate the following sequence:
14 * 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
15 *
16 * It can be seen that this sequence (starting at 13 and finishing at 1) contains
17 * 10 terms. Although it has not been proved yet (Collatz Problem), it is thought
18 * that all starting numbers finish at 1.
19 *
20 * Which starting number, under one million, produces the longest chain?
21 *
22 * NOTE: Once the chain starts the terms are allowed to go above one million.
23 *
24 * @return {number}
25 */
26exports.p0014 = function() {
27    let biggestSeen = 0;
28    let biggestIdx = 0;
29    const cache = new Map();
30    for (let x = 1; x < 1000000; x += 1) {
31        const result = collatzLen(x, cache);
32        if (result > biggestSeen) {
33            biggestSeen = result;
34            biggestIdx = x;
35        }
36    }
37    return biggestIdx;
38};
39
40/**
41 * @param {number} n
42 * @param {Map} cache
43 * @return {number}
44 */
45function collatzLen(n, cache) {
46    if (n == 1) {
47        return 0;
48    } else if (cache.has(n)) {
49        return cache.get(n);
50    } else if (n % 2 == 0) {
51        const result = 1 + collatzLen(n / 2, cache);
52        cache.set(n, result);
53        return result;
54    } else {
55        const result = 2 + collatzLen((3 * n + 1) / 2, cache);
56        cache.set(n, result);
57        return result;
58    }
59}

Tags: collatz, recursion, longest-path