Skip to content

Instantly share code, notes, and snippets.

@thomas4g
Created March 18, 2012 01:55
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 thomas4g/2067757 to your computer and use it in GitHub Desktop.
Save thomas4g/2067757 to your computer and use it in GitHub Desktop.
Find Collatz Chain Length
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