Skip to content

Instantly share code, notes, and snippets.

@NateWarner
Last active August 21, 2018 20:09
Show Gist options
  • Save NateWarner/fe1cfd1e95da0cb4af6e to your computer and use it in GitHub Desktop.
Save NateWarner/fe1cfd1e95da0cb4af6e to your computer and use it in GitHub Desktop.
Tail Call Optimization for Recursive Fibonacci - JS
// Attempting to solve for a tail call optimization on fibonacci
// Nate Warner
// 2015-01-14
'use strict';
function fibonacci(len) {
function recur(len, origLen, oldVal, newVal) {
return (len === origLen)
? newVal
: recur(len + 1, origLen, newVal, oldVal + newVal);
}
return recur(1, len, 0, 1);
}
console.log(fibonacci(27));
@bennycode
Copy link

bennycode commented Jun 14, 2017

This algorithm seems to be wrong because it returns 610 when asking for the Fibonacci number of 14. The correct result is 377.

610 would be the correct result when asking for the Fibonacci number of 15.

@NateWarner
Copy link
Author

Apologies for the late reply, @bennyn. Just saw this.

You were absolutely right. I was adding oldVal to newVal on the final return and that was incorrect. I've updated the gist. Thanks for letting me know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment