用于求解 a 的 b 次方,b是一个非常大的数,可以在O(logn)的复杂度求解。
ll pow(ll a,ll b,ll mod)
{
ll res=1;
while(b>0)
{
if(b&1)
res=(res*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return res;
}
求一个矩阵的很大的次方幂,例如斐波那契数列可以用矩阵来求
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
typedef long long LL;
const int N = 10000;
mat mul(mat a,mat b) //矩阵相乘
{
mat c(a.size(),vec(b[0].size()));
for(int i=0;i<a.size();i++)
{
for(int k=0;k<b.size();k++)
{
for(int j=0;j<b[0].size();j++)
c[i][j] = ( c[i][j] + a[i][k] * b[k][j] ) % N;
}
}
return c;
}
mat pow(mat a,int n) //快速幂
{
mat b(a.size(),vec(a.size()));
for(int i=0;i<a.size();i++)
b[i][i]=1;
while(n>0)
{
if(n & 1)
b=mul(b,a);
a=mul(a,a);
n >>= 1;
}
return b;
}
LL n;
int main()
{
mat a(2,vec(2));
while(~scanf("%d",&n)&&n!=-1)
{
a[0][0]=1,a[0][1]=1;
a[1][0]=1,a[1][1]=0;
a=pow(a,n);
printf("%d\n",a[1][0]);
}
return 0;
}