Code of the Day: Javascript Fibonacci Numbers the fast way


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
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:

Output for 0 to 4

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

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube