Daily Archives: April 18, 2011

Code of the Day: Javascript Fibonacci Numbers the fast way

1
2
3
4
5
6
7
8
//Programmer: Larry Battle
//Date: April 18, 2011
//Purpose: Get Fibonacci numbers in O(1) time.
var getFibonacciNum = function( n ){
    var s5 = Math.sqrt(5);
    var phi1 = (1+s5)/2, phi2 = (1-s5)/2;
    return Math.round((Math.pow( phi1, n ) - Math.pow( phi2, n) )/s5);
};

Demo: Here
Output for 0 to 4

F(0) = 0
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

More Posts - Website

Follow Me:
Twitter