JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
JavaScript
//Gets next number in the sequence
const nextNumber = iCurrent => iCurrent % 2 ? iCurrent * 3 + 1 : iCurrent / 2;
//calculates sequence length for starting value
function sequenceLength(iStart, oLengthMap){
let iLen = oLengthMap.get(iStart);
if(iLen){
return iLen;
}
const iNext = nextNumber(iStart);
iLen = sequenceLength(iNext, oLengthMap) + 1;
oLengthMap.set(iStart, iLen);
return iLen;
}
//finds number, under specified value, which has longest Collatz sequence length
function maxCollatzLength(iMaxValue){
//store subproblem results to improve performance with Dynamic Programming
const oLengthMap = new Map([[1,1]]);
//remember best result found so far
let iLongestSequence = 1;
let iLongestFor = 1;
for(let iCurrentLength, i=2; i<iMaxValue; i++){
iCurrentLength = sequenceLength(i, oLengthMap);
if(iCurrentLength > iLongestSequence){
iLongestSequence = iCurrentLength;
iLongestFor = i;
}
}
return iLongestFor;
}
console.log(maxCollatzLength(1000000)); //837799