Fibonacci numbers (JavaScript)
From LiteratePrograms
- Other implementations: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET
The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by
- 1 \\ \end{cases} ."/>
Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.
Contents |
Implementation
The [fibonacci] numbers in JavaScript:
<<fib.js>>= fib fastfib testdriver
Recursive
This is a very simple recursive implementation. This will become slow on big numbers, because the numbers are recalculated for each recursion.
<<fib>>= function fib(n){ return n<2?n:fib(n-1)+fib(n-2); }
Iteration
Although it is based directly on the definition of a Fibonacci number, the recursive Fibonacci algorithm is extremely expensive, requiring time O(2n). It also performs a huge amount of redundant work because it computes many Fibonnaci values from scratch many times. A simple linear-time iterative approach which calculates each value of fib successively can avoid these issues. The result from the 2 last calculations are stored in a dynamic array, to avoid all the recalculations in the recursive implementation.
<<fastfib>>= function fastfib(n){ var i; var fibs = new Array();
We start by push
ing the first two values into the array, which is initially empty.
<<fastfib>>= fibs.push(0); fibs.push(1);
The heart of the function is a for-loop. In each iteration of the loop we first push
the sum of the current values of the array onto the end of the array, and then shift
the array to remove the first element of the array. Thus, the first iteration will proceed like this:
fibs initially [0,1] fibs.push(fibs[0] + fibs[1]); fibs now [0,1,1] fibs.shift(); fibs now [1,1]
The actual implementation is
<<fastfib>>= for(i=0; i<n; i++){ fibs.push(fibs[0] + fibs[1]); fibs.shift(); } return fibs[0]; }
Test driver
<<testdriver>>= for(i=0; i<=20; i++) document.write("fib(" + i + ") = " + fib(i) + "<br/>"); for(i=0; i<=20; i++) document.write("fastfib(" + i + ") = " + fastfib(i) + "<br/>");
Download code |