Skip to content

Instantly share code, notes, and snippets.

@Mike-Dunton
Last active August 9, 2016 21:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mike-Dunton/7567554 to your computer and use it in GitHub Desktop.
Save Mike-Dunton/7567554 to your computer and use it in GitHub Desktop.
Collatz conjecture in js
// Return Collatz sequence in an array.
// Linear Vs Tail Recursion in Javascript
// http://jsperf.com/collatz-conjecture-linear-vs-tail
//===================================================================================================================
function collatzTail(n, accumulator){
if(n === 1) {
accumulator.push(1);
return accumulator;
} else if(isEven(n)) {
accumulator.push(n);
return collatzTail(n/2, accumulator);
} else {
accumulator.push(n);
return collatzTail(3*n+1, accumulator);
}
};
function collatzLinear(n){
if(n === 1)
return [1];
else if(isEven(n))
return [n].concat(collatzLinear2(n/2));
else
return [n].concat(collatzLinear2(3*n+1));
}
function isEven(NaturalNumber) {
return (NaturalNumber%2==0) ? true : false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment