Skip to main content

Modular Fibonacci Matrix

hard
MathNumber TheoryDivide And ConquerModular Exponentiation
Asked atGoogleJane StreetCitadelGoldman Sachs

Problem Description

The Fibonacci sequence is defined as F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2).

Given two integers `n` and `mod`, return **F(n) mod `mod`**.

Because `n` can be astronomically large, a naive iterative approach is too slow. Use matrix exponentiation to compute the answer in O(log n) time.

**Example 1:**
```
Input: n = 10, mod = 1000
Output: 55
Explanation: F(10) = 55; 55 mod 1000 = 55.
```

**Example 2:**
```
Input: n = 50, mod = 1000000007
Output: 586268941
Explanation: F(50) = 12586269025; 12586269025 mod 10^9+7 = 586268941.
```

Constraints

  • 0 <= n <= 10^18
  • 2 <= mod <= 10^9

Follow-up

Extend your solution to compute the sum F(0) + F(1) + ... + F(n) mod `mod` in O(log n) using a 3×3 matrix.

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.