Skip to content

Instantly share code, notes, and snippets.

@thiagoa
Last active July 13, 2017 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagoa/4a462101a7ec2b2b314686041ee5f313 to your computer and use it in GitHub Desktop.
Save thiagoa/4a462101a7ec2b2b314686041ee5f313 to your computer and use it in GitHub Desktop.
const MAX = 1000000;
const cache = new Array(MAX);
function nextFor(n) {
if (n == 1) {
return 1;
}
else if (n <= MAX && cache[n - 1] !== undefined) {
return cache[n - 1];
}
else if (n % 2 == 0) {
return 1 + nextFor(n / 2);
}
else {
return 1 + nextFor(n * 3 + 1);
}
}
function longestLength() {
let n = 1;
let maxN = 0;
let maxLength = 0;
while (n <= MAX) {
const length = nextFor(n);
cache[n - 1] = length;
if (length > maxLength) {
maxN = n;
maxLength = length;
}
n++;
}
return [maxN, maxLength];
}
console.log(longestLength());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment