快速幂及矩阵
基础快速幂
#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
int qpow(int a,int b,int mod)
{
int res=1;
for(ll i=1;i<=b;i<<=1,a=((ll)a*a)%mod)
if(i&b)res=((ll)res*a)%mod;
return res;
}
int main()
{
ll b, p, k;
cin>>b>>p>>k;
cout<<b<<"^"<<p<<" mod "<<k<<"="<<qpow(b,p,k);
return 0;
}
矩阵快速幂
#include<iostream>
#include<cstdio>
using namespace std;
const int P=1e9+7;
typedef long long ll;
struct matrix
{
int s[2][2];
};
matrix mul(matrix a, matrix b)
{
matrix ans;
int i,j,k;
for(i = 0; i < 2; i ++)
for(j = 0; j < 2; j ++)
for(k = 0; k < 2; k ++)
ans.s[i][j]=((ll)ans.s[i][j] + (ll)(a.s[i][k] * b.s[k][j]) % P) % P;
return ans;
}
matrix power(matrix a, int n)
{
matrix im;//单位矩阵
im.s[0][0] = im.s[1][1] = 1;
im.s[1][0] = im.s[0][1] = 0;
matrix b = a;
for(int i = 1; i <= n; i <<= 1, b = mul(b, b))
if(n & i) im = mul(im, b);
return im;
}
应用:求斐波那契数列
int F(int n)
{
if (n == 0) return 1 % P;
else if(n == 1) return 1 % P;
else
{
matrix a;
a.s[0][0] = a.s[0][1] = a.s[1][0] = 1;
a.s[1][1] = 0;
a = power(a, n - 2);
int f = (long long) (a.s[0][0] + a.s[0][1]) % P;
return f;
}
}
int main()
{
int n;
scanf("%d", & n);
cout << F(n) << endl;
return 0;
}