The Fibonacci sequence is the sequence defined by F(0) = 0, F(1) = 1, F(n + 2) = F(n) + F(n + 1). The first few terms are 0, 1, 1, 2, 3, 5, 8.
The Fibonacci sequence is the sequence defined by
F(0) = 0
F(1) = 1
F(n + 2) = F(n) + F(n + 1).
The first few terms are 0, 1, 1, 2, 3, 5, and 8.
The most efficient way to compute the first N values is to iterate over an array using the above formula, resulting in O(N)
operations (O(N²)
if digit or bit operations are counted). The recursive implementation should be generally avoided, since it is O(φN)
where φ
is the golden ratio and is equal to (1+sqrt(5))/2
. However, by using a cache for already computed values, it can be as fast as the iterative implementation.
One efficient method for computing single Fibonacci numbers is
Fib(n) = Round( Power( 0.5*(1+Sqrt(5)), n ) / Sqrt(5) );
The square root and power have to be computed in sufficient precision, roughly, Fib(n) requires about 0.2*n decimal digits or about 0.7*n bits in the integer result.
Another method is based on the fact that the matrix
( Fib[n+1] Fib[ n ] )
( Fib[ n ] Fib[n-1] )
is the n-th power of the matrix
( 1 1 )
which is ( Fib[2] Fib[1] )
( 1 0 )
equal to ( Fib[1] Fib[0] )
This is the basis of a halving-and-squaring method that computes Fib[N] in O(log(N))
operations, completely in (big) integer arithmetic.
If one accounts for the complexity of big integer multiplication, the complexity raises to O( M(N) ) digit or bit operations, where M(d) is the complexity of the multiplication of numbers of bit length d. Typical methods have M(d)=O(d*log(d)) for FFT based multiplication, M(d)=O(dw) with w=log2(3) for Karatsuba and smaller w for the Toom-Cook methods.