Skip to content

Instantly share code, notes, and snippets.

@abruzzihraig abruzzihraig/fibonacci
Last active Aug 29, 2015

Embed
What would you like to do?
Fibonacci tail recursion
function fib(n) {
var s = n1 = n2 = i = 1;
for (; i < n; i++) {
s = n1 + n2;
n1 = n2;
n2 = s;
}
return n1;
}
function fib2(n) {
return function(n) {
if (n === 0) return 0;
if (n === 1) return 1;
return arguments.callee(n - 1) + arguments.callee(n - 2);
}(n);
}
function fib3(n) {
return function(n1, n2, i) {
return (i < n) ? arguments.callee(n2, n1 + n2, i + 1) : n1;
}(0, 1, 1);
}
console.log(fib(2) + ',' + fib2(2) + ',' + fib3(2));
console.log(fib(4) + ',' + fib2(4) + ',' + fib3(4));
console.log(fib(5) + ',' + fib2(5) + ',' + fib3(5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.