Fib [solution]

by leethelobster

HTML

<div>
    <p>
    In the Fibonnaci sequence, each following number is the sum of its previous 2 numbers. The first few values in the Fibonnaci sequence are [0,1,1,2,3,5,8]
        
    <br>
    <br>
        Write a function that outputs answers to the Fibonnoci sequence when called with an input. 
    <br><br>
     <i>i.e. <br>fib(6)=8<br>fib(0)=0<br>fib(36)=??</i> 
    </p>
</div>

JavaScript

var fib = function(test)
{
    if(test == 0) return 0;
    if(test == 1) return 1;
    return fib(test-1) + fib(test-2);
}

console.log(fib(8));

////

var fibArray = [0,1]

function fib(__input){
    //check to see if it exists
    if(fibArray[__input] == null){
         var prev1 = fibArray[fibArray.length-1];
         var prev2 = fibArray[fibArray.length-2];
         //add the two previous numbers and extend array
         fibArray.push(prev1+prev2);
        //recursion, call it again untill there's an answer
         return fib(__input);
    } else {
        return fibArray[__input];
    }
}


console.log(fib(6));