-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrix Exponentiation.cpp
111 lines (92 loc) · 1.95 KB
/
Matrix Exponentiation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using namespace std;
#include<bits/stdc++.h>
typedef long long int ll;
#define MOD 1000000007
struct Matrix
{
int n, m;
vector <vector <int>> mat;
Matrix() {}
Matrix(int _n, int _m)
{
n = _n, m = _m;
mat = vector <vector <int>> (n, vector <int> (m));
}
void print()
{
cout << "MATRIX :: " << n << " " << m << endl;
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < m; ++j)
printf("%d ", mat[i][j]);
printf("\n");
}
}
};
Matrix Multiply(Matrix a, Matrix b, int Mod)
{
Matrix c = Matrix(a.n, b.m);
for(int i = 0; i < a.n; ++i)
{
for(int j = 0; j < b.m; ++j)
{
c.mat[i][j] = 0;
for(int k = 0; k < a.m; ++k)
{
c.mat[i][j] += (1LL * a.mat[i][k] * b.mat[k][j]) % Mod;
c.mat[i][j] %= Mod;
}
}
}
return c;
}
Matrix Add(Matrix a, Matrix b, int Mod) {
Matrix c = Matrix(a.n, a.n);
for(int i = 0; i < a.n; ++i)
{
for(int j = 0; j < a.n; ++j)
{
c.mat[i][j] = a.mat[i][j] + b.mat[i][j];
c.mat[i][j] %= Mod;
}
}
return c;
}
Matrix Pow(Matrix a, ll p, int Mod) {
if(p == 1)
return a;
Matrix x = Pow(a, p/2, Mod);
x = Multiply(x, x, Mod);
if(p&1)
x = Multiply(x, a, Mod);
return x;
}
ll calc(ll n)
{
if(n < 2)
return 1;
Matrix M = Matrix(2, 2);
M.mat[0][0] = 1;
M.mat[0][1] = 1;
M.mat[1][0] = 1;
M.mat[1][1] = 0;
Matrix A = Matrix(2, 1);
A.mat[0][0] = 1;
A.mat[1][0] = 0;
M = Pow(M, n-1, MOD);
M = Multiply(M, A, MOD);
return (M.mat[0][0] + M.mat[1][0]) % MOD;
}
int main()
{
ll n, m, x, y, t;
cin >> t;
while(t--)
{
cin >> n >> m;
x = calc(n)-1;
y = calc(m+1)-1;
cout << (y - x + MOD) % MOD << endl;
}
return 0;
}