2016/5/24

How to find a fibonacci number recursively with Javascript

I am learning programming languages with Codecademy for fun. Even though there are many answers on the same topic already, I just want to document the time I spent.

To find a fibonacci number, you simply add the previous two numbers: 1, 1, 2, 3, 5, 8, 13, 21, 44, 55, ...

The following is the code sample practice I did on Codecademy:


var count = 0;

// Recursively find Xth Fibonacci number 
var fib = function(x){
    // Keeps track of the amount of work done computing a Fibonacci
    count++;

    // Base Case
    if (x<=0) {return 0;}//**Optional**
    if(x<=2){return 1;}
    // Recursive calls
    return fib(x - 1) + fib(x - 2);
};

var f = fib(10);
console.log("It took "+count+" calculations to find that the 10th fibonacci number is "+f+".");

Note that the Big O efficiency of this algorithm is exponential, O(x^n), which is awfully slow.
It will take 109 calculations to find the 10th fibonacci number.

沒有留言: