Created
February 17, 2016 21:06
-
-
Save zzarcon/c3a80a9a4cc0a9ec4fc1 to your computer and use it in GitHub Desktop.
Javascript Fibonacci
This file contains 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(num) { | |
if (num <= 1) return 1; | |
return fibonacci(num - 1) + fibonacci(num - 2); | |
} |
var fibonacci = function (n) {
if (n <= 1) {
return n;
}
var f1 = 0;
var f2 = 1;
var f;
for (var i = 2; i <= n; i++) {
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
};
var fibonacciRecursive = function (n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just wanted to point out that the first if should return n, not 1, otherwise
fib(2) = 2
, when it should be 1.const fib = (n) => { return n <= 1 ? n : fib(n - 1) + fib(n - 2); }
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
....