Problem 234
Fibonacci Modulo for Huge N
Hard · 30 pts · Math, Matrix Exponentiation, Divide and Conquer
Problem
The Fibonacci numbers are F(0) = 0, F(1) = 1 and F(n) = F(n - 1) + F(n - 2). Print F(N) modulo 1000000007. N can be as large as 10^18, so computing the terms one by one is impossible. Use matrix exponentiation. The matrix [[1, 1], [1, 0]] raised to the power N contains F(N) in its top-right entry, and the power can be computed with O(log N) matrix multiplications by repeated squaring. Fast doubling (using F(2k) and F(2k + 1) formulas) is an equivalent alternative. The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).
Input
A single integer N.
Output
Print F(N) mod 1000000007.
Constraints
0 <= N <= 10^18
Example input
10
Example output
55
Explanation
The sequence begins 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, so F(10) = 55. Since 55 is smaller than 1000000007, the answer is 55.