JSFiddle - React, Tailwind, and code Playground
HTML
Starting number <span id="startingNumber"></span> has the longest chain (<span id="chainLength"></span> numbers):
<div id="chain"></div>
JavaScript
// Let's remember how long a chain is for a certain starting number
// We know that starting number 1 has chain length 1
let oChainLengths = { 1: 1 };
// Now go calculate all starting numbers under 1 million
for (i = 2; i < 1000000; i++) {
// Our starting number n is i
let n = i;
// And we start with an empty chain length
let iChainLength = 0;
// While we don't find a number already calculated, go calculate the next one
while (!oChainLengths[n]) {
// Calculate next number
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
iChainLength++;
}
// Remember the result
// I tried to remember in-between values, but pushing them to an array and looping over it took more time than this
oChainLengths[i] = iChainLength + oChainLengths[n];
}
// Find the starting number with the longest chain
const iAnswer = Object.keys(oChainLengths).reduce((iMax, n) => oChainLengths[n] > oChainLengths[iMax] ? n : iMax, 1);
// Just return one integer value
console.log(iAnswer); // 837799
// Additional code to show the answer to the public :-)
document.getElementById("startingNumber").innerHTML = iAnswer;
document.getElementById("chainLength").innerHTML = oChainLengths[iAnswer];
// Ok, why not show this chain...
let n = iAnswer;
let aChain = [n];
while (n !== 1) {
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
aChain.push(n);
}
document.getElementById("chain").innerHTML = aChain.join("<br/>");