Fibonacci solution in JavaScript

By | September 4, 2017

In mathematical terms, the Fibonacci sequence is a series of numbers in which each number is the sum of the two previous numbers. The sequence Fn is defined by:

Fn = Fn-1 + Fn-2, with seed values F1 = 1, F2 = 1  or  F0 = 0, F1 = 1.

So, for example, assuming seed values of 0 and 1, the sequence may look like:

0, 1, 1, 2, 3, 5, 8, 13

In this example, the result for F7  is 13.

Logically, the javascript code should look something like this:

var myFib2 = function (n) {
if (n <= 2) { return 1; }
else { return myFib2(n – 1) + myFib2(n – 2); }
};

This works but the code is inefficient with large indices. A more efficient solution is:

var myFib = function (n) {
var curr_n;
var f = function (b, a) {
var x = curr_n === 1? 1: (a || 0) + b;
return curr_n++ < n? f(x, b): x;
};
return (f(curr_n = 0));
};

Thanks to my friend SB for assisting with the improved solution. Check out the fiddle here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.