Fibonacci Sequence

Iteratively and Recursively

Fibonacci via Wikipedia:
By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

An example of the sequence can be seen as follows:

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 … 

Solution - Iteratively


var looping = function(n) {
    var a = 0, b = 1, f = 1;
    for(var i = 2; i <= n; i++) {
        f = a + b;
        a = b;
        b = f;
    }
    return f;
};
						

Solution - Recursively


var recursive = function(n) {
    if(n <= 2) {
        return 1;
    } else {
        return this.recursive(n - 1) + this.recursive(n - 2);
    }
};
						
Recursion can be a little tricky to wrap your head around. In the above code, we are going to plan on receiving the sequence value at index five because anything larger is going to be rough to type out. You can break this down like the following:

You can see above that on every line it is one further iteration through the recursive process. Based on our function logic, as soon as n <= 2 then we just return a value of one. At the furthest breakdown, our sum turns into five which is the Fibonacci number at index five.

Source: The Polygot Developer