Skip to content
StackDecode
Number theory & mathAnimated

Fast Doubling Fibonacci

Compute F(2k) and F(2k+1) from F(k) and F(k+1).

Time

O(log n)

Extra space

O(log n)

Use it for

Huge Fibonacci numbers.

How it works

  1. Use the identities F(2k) = F(k)·(2·F(k+1) − F(k)) and F(2k+1) = F(k)² + F(k+1)².
  2. To get F(n), get F(⌊n/2⌋) and F(⌊n/2⌋ + 1), then double.
  3. The recursion halves n each time, so it takes O(log n) steps instead of O(n).

Watch it run

Loading animation…