2018-3-24

Find longest Collatz sequence using Javascript

Solution to the 14th Project Euler problem – Longest Collatz Sequence - in both Kotlin and Javascript.

The 14th Project Euler problem - Longest Collatz Sequence - is stated as follows. Which starting number, under one million, produces the longest Collatz conjecture sequence?

const memoize = fn => {
    let cache = {};
    return n => cache[n] = cache[n] ? cache[n] : fn(n);
};

const getColatzLength = memoize(n => n <= 1 ? 1 : 1 + getColatzLength(n % 2 === 0 ? n / 2 : n * 3 + 1));

const [first] = new Array(1000000).fill()
    .map((_, index) => index)
    .map(n => getColatzLength(n))
    .map((len, n) => ({len, n}))
    .sort((a, b) => b.len - a.len);
Jan Järfalk — User experienced esthete, technician, geek and web worker. Aspiring artist and recreational mathematician. I indulge and travel plenty. Constraints are good.