Fibonacci Numbers
There are various problems that play with the Fibonacci numbers, so we need to look into these as well. They form a series and are defined like this:
Definition: Fibonacci Numbers
The Fibonacci numbers for them infinite natural number sequence
Efficient computation
Although the definition is recursive, one shouldn't compute them in a recursive way. Otherwise one will have to recompute terms that one had computed before and end up with an
Example: Let's compute
You can see that we need to compute
Iterative generation
It is much better to use an iterative algorithm:
- Set
, . - Iterate …
- Yield
. - Set
. - Set
. - Set
.
- Yield
This will yield 1, 1, 2, 3, 5, … as we want.
It never recomputes any number. Therefore the complexity here is
Computation in O(log n)
If we want to compute
Theorem: n-th Fibonacci Number by Exponentiation
together with exponentiation by squaring.
Proof
The above iterative algorithm can also be expressed in matrix form:
We can apply this matrix over and over in order to advance in the algorithm. Hence we can write a closed-form expression:
The exponentiation of the matrix would be
Eigenvalue trick for O(1)
There is an eigenvalue trick that one can use to directly compute any Fibonacci number in closed form:
Theorem: n-th Fibonacci Number via Eigenvalues
The
Proof
We start with the closed-form expression from the other theorem:
We will do an eigensystem decomposition of the matrix in order efficiently compute its exponentiation. Let's call the matrix in the middle
The associated eigenvectors are
We collect these into an eigenvalue matrix
Hence we can write the matrix
The inverse of
Putting all of that together gives us
The real simplification comes from writing out
Because
We can then plug in all the expressions and we arrive at
As we're only interested in
This expression doesn't work well numerically as one has to project high powers of an irrational number (the inf results.
Numerical approximation
We can work with the logarithm to make it more tractable.
Theorem
The
Proof
We have