Last active
July 13, 2017 14:42
-
-
Save thiagoa/4a462101a7ec2b2b314686041ee5f313 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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