Skip to content

Instantly share code, notes, and snippets.

@zackthehuman
Created March 29, 2012 06:03
Show Gist options
  • Save zackthehuman/2233928 to your computer and use it in GitHub Desktop.
Save zackthehuman/2233928 to your computer and use it in GitHub Desktop.
Fibonacci using recursion and iteration
// 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