提高+省选-专题[数论][矩阵快速幂]:P1306 斐波那契公约数
题目
华丽的分割线
分析
gcd(F[n],F[m])=F[gcd(n,m)]gcd(F[n],F[m])=F[gcd(n,m)]
这个公式成功将问题转化为求F[gcd(n,m)]的值
1.先用辗转相除求gcd(n,m)
2.用矩阵快速幂加速递推
代码
#include<cstdio>
#define ll long long
using namespace std;
ll p;
ll gcd(ll a,ll b)
{
if(b==0)
{
return a;
}
else
{
return gcd(b,a%b);
}
}
struct node
{
ll num[10][10];
friend node operator * (node x1,node x2);
};
node operator * (node x1,node x2)
{
int i,j,k;
node x3;
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
x3.num[i][j]=0;
for(k=1;k<=2;k++)
{
x3.num[i][j]=(x3.num[i][j]%p+(x1.num[i][k]%p*x2.num[k][j]%p)%p)%p;
}
}
}
return x3;
}
int main()
{
p=100000000;
ll n,m,k;
scanf("%lld%lld",&n,&m);
k=gcd(n,m);
node x1;
x1.num[1][1]=1;
x1.num[1][2]=1;
x1.num[2][1]=1;
x1.num[2][2]=0;
node ans;
ans.num[1][1]=1;
ans.num[1][2]=1;
ans.num[2][1]=0;
ans.num[2][2]=0;
if(k==1||k==2)
{
printf("1");
return 0;
}
else
{
k=k-2;
while(k!=0)
{
if(k%2==1)
{
ans=ans*x1;
}
x1=x1*x1;
k=k/2;
}
printf("%lld",ans.num[1][1]);
}
}