## Calculating Fibonacci numbers

The Fibonacci sequence is defined by

*f*_{1} = 1

*f*_{2} = 1

*f*_{n}
= *f*_{n-1}
+ *f*_{n-2}

and is solved by

*f*_{n}
= [φ^{n} -
(1*-*φ)^{n}] */ sqrt*(5)

= φ^{n} / sqrt(5)
rounded to the nearest integer

where φ = [1 + *sqrt*(5)] / 2 = 1.61803...
However, for large *n* this would need extraordinary precision
to calculate.

Here are three methods to calculate *f*_{n},
each successive method exponentially more efficient
than its predecessor.

__Recursion__:

__Fib1__(n)
**if** n ≤ 2 **then return** 1
**else return** ( Fib1(n-1) + Fib1(n-2) )

T(*n*) =
Θ(φ^{n})

__Dynamic programming__:

__Fib2__(n)
i := 1
j := 1
**for** k := 3 **to** n **do**
j := i+j
i := j-i
**return** j

T(*n*) = Θ(*n*)

__Divide-and-conquer__:

__Fib3__(n)
i := 1
j := 0
k := 0
h := 1
**while** n > 0 **do**
**if** n is odd **then**
t := jh
j := ih + jk + t
i := ik + t
t := h^{2}
h := 2kh + t
k := k^{2} + t
n := floor( n/2 )
**return** j

T(*n*) = Θ(log *n*)

*Fib3* works by making use of the fact that

_ _ n _ _
| 0 1 | | f_{n-1} f_{n } |
| | = | |
|_ 1 1 _| |_ f_{n } f_{n+1} _|