Here’s a classic way to get Fₙ in O(log n) time (arithmetic-operation count), via “fast doubling.” The idea is to exploit these identities for any k:
F₂k = Fk·(2·F_{k+1} − Fk)
F₂k+1 = F_{k+1}² + Fk²
Once you can compute (Fₖ, Fₖ₊₁) in time T(k), you can compute (F₂ₖ, F₂ₖ₊₁) by a constant number of multiplies/adds, so
T(2k) ≈ T(k) + O(1).
By recursion, T(n) = O(log n).
Pseudocode (recursive)
function fib_pair(n):
# returns (F_n, F_{n+1})
if n == 0:
return (0, 1)
(a, b) = fib_pair( n // 2 ) # a = F_k, b = F_{k+1}, k = floor(n/2)
c = a * (2*b - a) # F_{2k}
d = a*a + b*b # F_{2k+1}
if n is even:
return (c, d)
else:
return (d, c + d)
function fib(n):
(fn, _) = fib_pair(n)
return fn
Explanation of steps
- Base case: fib_pair(0) = (F₀, F₁) = (0, 1).
- Recurse on k = ⌊n/2⌋, getting (Fₖ, F_{k+1}).
- Compute
- F₂ₖ = Fₖ·(2·F_{k+1} − Fₖ)
- F₂ₖ₊₁ = Fₖ² + F_{k+1}²
- If n is even, you’ve got (Fₙ, Fₙ₊₁) = (F₂ₖ, F₂ₖ₊₁);
if odd, shift: (Fₙ, Fₙ₊₁) = (F₂ₖ₊₁, F₂ₖ + F₂ₖ₊₁).
Each level of recursion halves n, so depth is O(log n), and at each level we do a constant number of multiplications/additions.
Iterative (bottom-up) variant
If you don’t like recursion, you can do the same doubling by looking at the binary expansion of n:
function fib(n):
# initialize (F, G) = (F₀, F₁) = (0,1)
F = 0; G = 1
# we’ll process bits of n from most significant to least
for bit in bits_of(n) from MSB down to LSB:
# first square step: compute (F₂k, F₂k+1) from (F, G)
F2k = F * (2*G - F)
F2k1 = F*F + G*G
if bit == 0:
(F, G) = (F2k, F2k1)
else:
(F, G) = (F2k1, F2k + F2k1)
return F
Here “bits_of(n)” is simply the binary digits of n (skipping the leading 0’s), so we do O(log n) iterations.
Complexity
- Arithmetic-operation count: O(log n).
- If you’re working with very large n (so Fₙ has ~n bits), then each “multiply” is not O(1) but e.g. O(M(log Fₙ)), so the bit-complexity becomes O(M(n)·log n), where M(b) is the cost to multiply two b-bit numbers (e.g. ~b log b with FFT methods).
But in the usual “Fₙ fits in a machine word” or “arithmetic ops are unit–cost” model, this runs in O(log n) time, beating the naïve O(n) DP.