Codility

Today, I was sent a link to Codility, a site for software developers.

On it's frontpage they ask  you to improve a little JavaScript function that calculate a specified Fibonacci number, complaining that the function takes a long time to do so.

Here's the original function at the site:

var yourself = {
    fibonacci : function(n) {
        if (n === 0) {
            return 0;
        } else if (n === 1) {
            return 1;
        } else {
            return this.fibonacci(n - 1) +
                this.fibonacci(n - 2);
        }
    }
};

And here's how I improved it:


var yourself = {
    fibonacci : function(n) {
        if (n === 0) {
            return 0;
        } else if (n === 1) {
            return 1;
        } else {
            return Math.floor(
                    (
                     (Math.pow(((1 + Math.sqrt(5)) / 2), n)) - 
                     (Math.pow(((1 - Math.sqrt(5)) / 2), n))
                    ) *
                     (1 / Math.sqrt(5))
                   );
        }
    }
};

Comments