haechandev
Algorithms

[Baekjoon 11444] Fibonacci Number 6

Computing a very large Fibonacci index with fast exponentiation of a 2×2 matrix.

August 26, 2022

The index n is too large to compute Fibonacci numbers one at a time. The recurrence can instead be represented by a matrix power.

|1 1|^n
|1 0|

The entries of this matrix power contain F(n+1) and F(n). I squared the matrix while halving the exponent.

  • For an even exponent, compute A^(n/2) and square it.
  • For an odd exponent, square it and multiply by the base matrix once more.

The recursion depth becomes log n instead of n. Applying the modulus at every multiplication also keeps the values bounded.

Problem: Baekjoon · Code: View on GitHub