Problem 3: Matrix Exponentiation for Fibonacci Numbers
Problem Statement: Compute the n-th Fibonacci number modulo 10^9+7 using matrix exponentiation.
Input
A single integer n.
Output
Print the n-th Fibonacci number modulo 10^9+7.
Examples
Input:
10
Output:
55
Solution in C++
#include <iostream>
#include <vector>
using namespace std;
const long long MOD = 1000000007;
struct Matrix {
long long m[2][2];
};
Matrix mul(const Matrix &A, const Matrix &B){
Matrix C = {{{0,0},{0,0}}};
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
for(int k=0;k<2;k++){
C.m[i][j] = (C.m[i][j] + A.m[i][k]*B.m[k][j]) % MOD;
}
}
}
return C;
}
Matrix power(Matrix A, long long n){
Matrix result = {{{1,0},{0,1}}};
while(n){
if(n & 1) result = mul(result, A);
A = mul(A, A);
n /= 2;
}
return result;
}
int main(){
long long n; cin >> n;
if(n == 0) { cout << 0; return 0; }
Matrix F = {{{1,1},{1,0}}};
F = power(F, n-1);
cout << F.m[0][0];
return 0;
}