Created
September 25, 2014 03:29
-
-
Save ryancole/78f2abe44674ef3f3840 to your computer and use it in GitHub Desktop.
fibonacci
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
function fibonacci (n) { | |
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); | |
}; | |
var fibonacci_memo = (function () { | |
var memo = [0,1]; | |
function fib (n) { | |
var result = memo[n]; | |
if (typeof result !== 'number') { | |
result = fib(n - 1) + fib(n - 2); | |
memo[n] = result; | |
} | |
return result; | |
}; | |
return fib; | |
}()); | |
for (var i = 0; i <= 40; i += 1) { | |
console.log('// ' + i + ': ' + fibonacci(i)); | |
} | |
for (var i = 0; i <= 40; i += 1) { | |
console.log('// ' + i + ': ' + fibonacci_memo(i)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment