# Fibonacci numbers (Ruby)

### 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 |

## Recursion

This simple ruby program uses recursion to print the first 10 Fibonacci numbers to the console.

<<fibonacci.rb>>=def fib(n)returnnif(0..1).include? n fib(n-1)+ fib(n-2)ifn > 1endtest main

This is a shorter version:

<<fibonacci_recursive2.rb>>=def fib(n)n < 2 ? n : fib(n-1)+ fib(n-2)endtest main

## Iteration

Although it is based directly on the definition of a Fibonacci number, the recursive Fibonacci algorithm is extremely expensive, requiring time *O*(2^{n}). 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:

<<fibonacci_iterative.rb>>=def fib(n)curr = 0 succ = 1 n.timesdo|i| curr, succ = succ, curr + succendreturncurrendtest main

## Array Method

The Array Method is an easier to read, linear computation that saves previous values to an array for lookup. This makes it much faster than recursion, though of course, uses more memory.

<<fibonacci_array.rb>>=def fib(n)returnnifn < 2 vals =[0, 1]n.timesdovals.push(vals[-1]+ vals[-2])endreturnvals.lastendtest main

## Matrix Method

While the iterative method does run in *O*(*n*) time we can still improve on this by understanding the following formula:

From this we can create a simple *O*(*l**g*(*n*)) time algorithm.

<<fibonacci_matrix.rb>>=require'matrix' FIB_MATRIX = Matrix[[1,1],[1,0]]def fib(n)(FIB_MATRIX**(n-1))[0,0]endtest main

## Testing

We can test all of the above implementations using a simple loop:

<<test main>>=10.timesdo|i|putsfib(i)end

Download code |