Created
October 16, 2016 23:42
-
-
Save jasonwaters/d6a099b7e1c98af298657b215395d9c3 to your computer and use it in GitHub Desktop.
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
| //1, 1, 2, 3, 5, 8, 13, 21 | |
| (function() { | |
| let result = []; | |
| window.fibonacci = function(n) { | |
| if (n < 1) { | |
| throw new Error("n must be greater than 0"); | |
| } | |
| n -= 1; | |
| let start = result.length; | |
| if (n >= start) { | |
| for (var i = start; i <= n; i++) { | |
| if (i < 2) { | |
| value = 1; | |
| } else { | |
| value = result[i - 2] + result[i - 1]; | |
| } | |
| result.push(value); | |
| } | |
| } | |
| return result[n]; | |
| } | |
| })(); | |
| console.log(fibonacci(100)); | |
| console.log(fibonacci(1)); | |
| console.log(fibonacci(2)); | |
| console.log(fibonacci(3)); | |
| console.log(fibonacci(4)); | |
| console.log(fibonacci(5)); | |
| console.log(fibonacci(6)); | |
| console.log(fibonacci(7)); | |
| console.log(fibonacci(8)); | |
| console.log(fibonacci(9)); | |
| console.log(fibonacci(10)); |
Author
jasonwaters
commented
Jan 27, 2017
Author
succinct and efficient
const fib = (function() {
let sequence = [1,1];
return function(n) {
while(n >= sequence.length) {
sequence.push(sequence[sequence.length-2] + sequence[sequence.length-1]);
}
return sequence[n];
}
})();
console.log(fib(6));
console.log(fib(1000));
console.log(fib(100));
console.log(fib(10));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment