快速幂&矩阵快速幂

 快速幂模板

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 
 5 int main()
 6 {
 7     ll a, b, c; cin >> a >> b >> c;
 8     ll aa = a, bb = b;
 9     ll ans = 1;
10     while (b >= 1)
11     {
12         if (b & 1)
13             ans = ans * a % c;
14         a = a * a % c;
15         b >>= 1;
16     }
17     printf("%lld^%lld mod %lld=%lld\n", aa, bb, c, ans % c);//注意:当b等于0的时候,结果为1,要单独对c取模,因为c可能为1.
18 }

 

矩阵快速幂模板

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const long long maxn = 110;
 5 long long mod = 1e9 + 7;
 6 struct matrix
 7 {
 8     long long v[maxn][maxn];
 9     long long n;
10 };
11 matrix mul(matrix a, matrix b)
12 {
13     matrix res;
14     res.n = a.n;
15     memset(res.v, 0, sizeof(res.v));
16     for (long long i = 1; i <= res.n; i++)
17         for (long long j = 1; j <= res.n; j++)
18             for (long long k = 1; k <= res.n; k++)
19                 res.v[i][j] += a.v[i][k] * b.v[k][j], res.v[i][j] %= mod;
20     return res;
21 }
22 signed main()
23 {
24     ll n, k; cin >> n >> k;
25     matrix a, res;
26 
27     a.n = res.n = n;
28     for (long long i = 1; i <= n; i++)
29         for (long long j = 1; j <= n; j++)
30             res.v[i][j] = i == j ? 1 : 0;
31     for (long long i = 1; i <= n; i++)
32         for (long long j = 1; j <= n; j++)
33             cin >> a.v[i][j];
34     while (k)
35     {
36         if (k & 1)
37             res = mul(res, a);
38         a = mul(a, a);
39         k >>= 1;
40     }
41     for (long long i = 1; i <= n; i++)
42         for (long long j = 1; j <= n; j++)
43             printf("%lld%c", res.v[i][j], j == n ? '\n' : ' ');
44 }

 

posted @ 2019-10-10 18:48  滚烫的青春  阅读(128)  评论(0编辑  收藏  举报