-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuva-10229-MatrixExp.cpp
More file actions
100 lines (77 loc) · 1.96 KB
/
uva-10229-MatrixExp.cpp
File metadata and controls
100 lines (77 loc) · 1.96 KB
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
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
int MOD[20];
int currentMod;
void multiply(ULL F[2][2], ULL M[2][2]); /// To calculate F = F * M
void power(ULL F[2][2], int n); /// To calculate F[2][2]^n in O(logn)
int powLogn(int power); /// To calculate 2^power in O(logn)
int findMod(int n, int m);
int main()
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n, m, ans;
while (scanf("%d%d", &n, &m) != EOF) {
if (n == 0) {
printf("0\n");
continue;
}
if (MOD[m] == 0) {
MOD[m] = powLogn(m);
}
currentMod = MOD[m];
ans = findMod(n, m);
printf("%d\n", ans % currentMod);
}
return 0;
}
void multiply(ULL F[2][2], ULL M[2][2])
{
ULL w = (((F[0][0] % currentMod) * (M[0][0] % currentMod)) % currentMod + ((F[0][1] % currentMod) * (M[1][0] % currentMod)) % currentMod) % currentMod;
ULL x = (((F[0][0] % currentMod) * (M[0][1] % currentMod)) % currentMod + ((F[0][1] % currentMod) * (M[1][1] % currentMod)) % currentMod) % currentMod;
/// x and y will have the same value
/// int y = F[1][0] * M[0][0] + F[1][1] * M[1][0];
ULL z = (((F[1][0] % currentMod) * (M[0][1] % currentMod)) % currentMod + ((F[1][1] % currentMod) * (M[1][1] % currentMod)) % currentMod) % currentMod;
F[0][0] = w;
F[0][1] = F[1][0] = x;
/// F[1][0] = y;
F[1][1] = z;
}
void power(ULL F[2][2], int n)
{
if (n <= 1) {
return;
}
power(F, n / 2);
multiply(F, F);
ULL M[2][2] = {
{1, 1},
{1, 0}
};
if (n % 2 != 0) {
multiply(F, M);
}
}
int powLogn(int power)
{
if (power == 0) {
return 1;
}
int temp = powLogn(power / 2);
if (power % 2 == 0) {
return temp * temp;
}
else {
return 2 * temp * temp;
}
}
int findMod(int n, int m)
{
ULL fib[2][2] = {
{1, 1},
{1, 0}
};
power(fib, n);
return (int) fib[0][1];
}