SAP Community Coding Challenge Nr.2
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="div1">
<h>||SAP Community Coding Challenge Nr.2||</h>
</div>
</body>
</html>
JavaScript
const memoize = (fn) => {
let cache = {};
return (...args) => {
let n = args[0];
if (n in cache) {
return cache[n];
}
else {
let result = fn(n);
cache[n] = result;
return result;
}
}
}
const collatz = memoize((n) => n === 1 ? 1 : 1 + collatz( n % 2 === 0 ? n / 2 : 3 * n + 1 ));
var longest_collatz = 0; output = 0;
let start = (new Date()).getTime()
for (var x = 1; x < 1000000; x++){
var x_longest_collats = collatz(x);
if (longest_collatz < x_longest_collats){
longest_collatz = x_longest_collats
output = x;
}
}
let end = (new Date()).getTime()
let performance = end - start;
// Output
var contCollatz = document.createTextNode("Longest Collatz Sequence: " + output + " - Processing Time: " + performance + " ms" );
document.body.appendChild(contCollatz)