Created
March 18, 2012 01:55
-
-
Save thomas4g/2067757 to your computer and use it in GitHub Desktop.
Find Collatz Chain Length
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
var nums = [], lengths = []; | |
function findNumLength(n) { | |
//preliminary check to see if | |
//we've done this number before | |
var indexOf = nums.indexOf(n); | |
if(indexOf !== -1) { | |
return lengths[indexOf]; | |
} | |
function even (n2) { return n2%2===0; } | |
if(n===1) { | |
return 1; | |
} | |
if(even(n)) { | |
l = findNumLength(n/2) + 1; | |
if(indexOf===-1) { | |
lengths.splice(0,0 ,l); | |
nums.push(n); | |
} | |
return l; | |
} | |
else { | |
l = findNumLength(3*n + 1) + 1; | |
if(indexOf===-1){ | |
lengths.splice(0,0,l); | |
nums.push(n); | |
} | |
return l; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment