Last active
August 9, 2016 21:49
-
-
Save Mike-Dunton/7567554 to your computer and use it in GitHub Desktop.
Collatz conjecture in js
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
// 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