However, for large n this would need extraordinary precision to calculate.
Here are three methods to calculate fn, 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 := h2
h := 2kh + t
k := k2 + t
n := floor( n/2 )
return j
T(n) = Θ(log n)
Fib3 works by making use of the fact that
_ _ n _ _
| 0 1 | | fn-1 fn |
| | = | |
|_ 1 1 _| |_ fn fn+1 _|