JSFiddle - React, Tailwind, and code Playground
HTML
<p>Type the maximum number a sequence should be find in: <input type="text" id="highestNumber" size="8" value="1000000"></p>
<button id="b" class="myButton">Calculate</button>
<p>Maximum length for a sequence is
<span id="maxSteps"></span> and highest number is <span id="maxNumber"></span></p>
<p>Time elapsed to calculate the result: <span id="time"></span></p>
JavaScript
let step_cache = new Map();
var theButton = document.getElementById("b");
theButton.onclick = main;
function stepCalculation(n) {
if (n == 1) {
return 0;
}
var steps = step_cache.get(n);
if (steps) {
return steps;
}
if (n % 2 == 0) {
steps = stepCalculation(n / 2) + 1;
} else {
//skip the map check for higher values, therefore do two steps in one
steps = stepCalculation((n * 3 + 1) / 2) + 2;
}
step_cache.set(n, steps);
return steps;
}
function main() {
var maxN = 0;
var maxS = 0;
var highestNumber = parseInt(document.getElementById("highestNumber").value);
var startTime = new Date();
var i;
//above the value 10545324, the map allocates more than 1GB of memory, which is not allowed
if (highestNumber && highestNumber <= 10545324) {
for (i = 1; i <= highestNumber; i++) {
var res = stepCalculation(i);
if (res >= maxS) {
maxS = res;
maxN = i;
}
}
var endTime = new Date();
var maxSteps = document.getElementById("maxSteps");
maxSteps.innerHTML = maxS;
var maxNumber = document.getElementById("maxNumber");
maxNumber.innerHTML = maxN;
var time = document.getElementById("time");
var timeDiff = endTime - startTime;
time.innerHTML = timeDiff + " ms";
} else {
window.alert("The input value for the maximum number is out of range.")
}
}