DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Fibonacci Without Loops Nor Recursions //JavaScript Function

11.07.2005
| 7140 views |
  • submit to reddit
        <a href="http://jsfromhell.com/math/fibonacci">

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

usage

for(var i = 11; --i > -11; document.write(i, " = ", fibonacci(i), "<br />"));

code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/fibonacci [v1.0]

fibonacci = function(n){
	return Math.round(Math.pow((Math.sqrt(5) + 1) / 2, Math.abs(n)) / Math.sqrt(5)) * (n < 0 && n % 2 ? -1 : 1);
};

/*this one requires very few recursions
fibonacci = function(n){
	var x;
	return n < 2 ? n : n % 2 ? (x = fibonacci(n = -(-n >> 1))) * x + (x = fibonacci(n - 1)) * x : (fibonacci(n >>= 1) + 2 * fibonacci(n - 1)) * fibonacci(n);
};
*/