Skip to content

Instantly share code, notes, and snippets.

@edfuh

edfuh/fibo.js

Created May 19, 2011
Embed
What would you like to do?
fibonacci functions
/// RECURSIVE
var fib = function (n) {
return n < 2 ? n : fib(n-1) + fib(n-2);
}
/// MEMOIZED
var memo = [0,1];
var fib = function(n) {
if (n >= memo.length) {
for (var i = memo.length; i <= n; i++) {
memo[i] = memo[i - 2] + memo[i - 1];
}
}
return memo[n];
}
/// MOAR BETTER MEMO?
var fib = function(n) {
fib.cache = fib.cache || [0,1];
if (n >= fib.cache.length) {
for (var i = fib.cache.length; i <= n; i++) {
fib.cache[i] = fib.cache[i - 2] + fib.cache[i - 1];
}
}
return fib.cache[n];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment