A Pen by Nate Warner on CodePen.
Last active
August 21, 2018 20:09
-
-
Save NateWarner/fe1cfd1e95da0cb4af6e to your computer and use it in GitHub Desktop.
Tail Call Optimization for Recursive Fibonacci - JS
This file contains hidden or 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
// 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)); |
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
This algorithm seems to be wrong because it returns
610
when asking for the Fibonacci number of14
. The correct result is377
.610
would be the correct result when asking for the Fibonacci number of15
.