矩阵快速幂求斐波那契

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int p=10000;
 4 typedef long long ll;
 5 int n,m;
 6 
 7 struct node {
 8     ll a[2][2];
 9 
10     node operator*(const node &b) const {
11         node res;
12         for (int i = 0; i < 2; i++) {
13             for (int j = 0; j < 2; j++) {
14                 res.a[i][j] = 0;
15                 for (int k = 0; k < 2; k++) {
16                     res.a[i][j] = (res.a[i][j] + a[i][k] * b.a[k][j]) % m;
17                 }
18             }
19         }
20         return res;
21     }
22 };
23 
24 node pow(node b,ll c) {
25     node res;
26     res.a[0][0] = 1;
27     res.a[1][0] = 0;
28     res.a[0][1] = 0;
29     res.a[1][1] = 1;
30     while (c) {
31         if (c & 1) {
32             res = res * b;
33         }
34         c >>= 1;
35         b = b * b;
36     }
37     return res;
38 }
39 
40 int main() {
41     node f;
42     f.a[0][0] = 1;
43     f.a[1][0] = 1;
44     f.a[0][1] = 1;
45     f.a[1][1] = 0;
46     scanf("%d%d", &n, &m);
47         node ans = pow(f, n);
48         printf("%lld
", ans.a[1][0]);
49 }
原文地址:https://www.cnblogs.com/Accpted/p/11203403.html