Skip to content

Instantly share code, notes, and snippets.

@zzarcon
Created Feb 17, 2016
Embed
What would you like to do?
Javascript Fibonacci
function fibonacci(num) {
if (num <= 1) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}
@VicFrolov
Copy link

VicFrolov commented Feb 28, 2017

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
....

Copy link

ghost commented Apr 20, 2019

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