Created
March 29, 2012 06:03
-
-
Save zackthehuman/2233928 to your computer and use it in GitHub Desktop.
Fibonacci using recursion and iteration
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
// These functions assume that fib(0) = 0, fib(1) = 1 | |
// In other words, 0 and 1 are the seeds of the sequence. | |
function recursiveFib(n) { | |
if(n < 0) { | |
throw "Negative numbers are not allowed."; | |
} | |
if(n < 2) { | |
return n; | |
} | |
return recursiveFib(n - 1) + recursiveFib(n - 2); | |
} | |
function iterativeFib(n) { | |
var fibs = [0, 1, 1], | |
i = 0; | |
if(n < 0) { | |
throw "Negative numbers are not allowed."; | |
} | |
if(n <= 2) { | |
return fibs[n]; | |
} | |
for(i = 3; i <= n; ++i) { | |
fibs[i] = fibs[i - 1] + fibs[i - 2]; | |
} | |
return fibs[n]; | |
} | |
console.log("Recursive: " + recursiveFib(8)); // => 21 | |
console.log("Iterative: " + iterativeFib(8)); // => 21 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment