haechandev
Algorithms

[Baekjoon 2086] Sum of Fibonacci Numbers

Reduce a Fibonacci range sum to two terms and compute them with matrix exponentiation.

September 1, 2022

Adding Fibonacci numbers from index a to b directly is too slow for the range. The sequence has the following identity:

F(1) + F(2) + ... + F(n) = F(n + 2) - 1

So the range sum becomes F(b + 2) - F(a + 1). I computed these two values with fast exponentiation of a 2×2 matrix.

Only the last nine digits are needed. When subtraction produced a negative result, I corrected it by adding the modulus. The core idea was to reduce a large range sum to two terms of a recurrence.

Problem: Baekjoon · Code: View on GitHub