Fibonacci //JavaScript Repository

Description

Fibonacci numeric sequence without loop/recursion.
Created: 2005.11.07

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/fibonacci [rev. #1]

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

/*
Version with fewer recursions
fibonacci = function(n){
    var o;
    return n < 2 ? n : n % 2 ? (o = fibonacci(n = -(-n >> 1))) * o + (o = fibonacci(n - 1)) * o : (fibonacci(n >>= 1) + 2 * fibonacci(n - 1)) * fibonacci(n);
};
*/

Example (Example)

<script type="text/javascript">
//<![CDATA[

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

//]]>
</script>

Help

fibonacci(n: Integer): Integer
Returns the number in the position "n" of the fibonacci sequence.
n
posição desejada

Rank (Votes: 25)

3.96