Since OP has asked about matrix solution not involving any floating point computations, here it is. We can achieve O(logn)
complexity this way, assuming numeric operations have O(1)
complexity.
Let's take 2x2 matrix A
having following structure
1 1
1 0
Now consider vector (8, 5)
, storing two consecutive fibonacci numbers. If you multiply it by this matrix, you'll get (8*1 + 5*1, 8*1 + 5*0) = (13, 8)
- the next fibonacci number.
If we generalize, A^n * (1, 0) = (f(n), f(n - 1))
.
The actual algorithm takes two steps.
- Calculate
A^2
, A^4
, A^8
, etc. until we pass desired number.
- Do a binary search by
n
, using calculated powers of A
.
On a side note, any sequence of the form f(n) = k1*f(n-1) + k2*f(n-2) + k3*f(n-3) + .. + kt*f(n-t)
can be presented like this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…