码迷,mamicode.com
首页 > 其他好文 > 详细

【斐波那契】【矩阵快速幂模板】斐波那契公约数

时间:2019-07-23 16:57:49      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:bit   lld   names   ++   print   name   inline   有一个   一个   

这道题求第n项和第m项斐波那契的公约数这里有一个定理(n,m都是1e9)

gcd(f[m],f[n])=f[gcd(n,m)]

斐波那契使用矩阵快速幂求

#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
using namespace std;
const int maxn=20010;
const int NIL=0;
const int mod=100000000;
ll n,m;
struct node
{
    ll a[3][3];
    ll x,y;
};
inline node mul(node a,node b)
{
    node tmp;
    memset(&tmp,0,sizeof(tmp));
    for(int i=0;i<a.x;i++)
    {
        for(int j=0;j<b.y;j++)
        {
            for(int k=0;k<a.y;k++)
            {
                tmp.a[i][j]=(tmp.a[i][j]+a.a[i][k]*b.a[k][j]%mod)%mod;
            }
        }
    }
    tmp.x=a.x;
    tmp.y=b.y;
    return tmp;
}
ll qm(ll b)
{
    node ant,tmp;
    memset(&tmp,0,sizeof tmp);
    memset(&ant,0,sizeof ant);
    tmp.x=2;
    tmp.y=2;
    tmp.a[0][0]=tmp.a[0][1]=tmp.a[1][0]=1;
    ant.x=1;
    ant.y=2;
    ant.a[0][0]=ant.a[0][1]=1;
    while(b)
    {
        if(b&1)
            ant=mul(ant,tmp);
        tmp=mul(tmp,tmp);
        b>>=1;
    }
    return ant.a[0][0];
}
ll gcd(ll a,ll b)
{
    if(b==0)
        return a;
    return gcd(b,a%b);
}
int main()
{
    scanf("%lld %lld",&n,&m);
    n=gcd(n,m);
    if(n<=2)
        printf("1\n");
    else
        printf("%lld\n",qm(n-2));
    return 0;
}

【斐波那契】【矩阵快速幂模板】斐波那契公约数

标签:bit   lld   names   ++   print   name   inline   有一个   一个   

原文地址:https://www.cnblogs.com/Diliiiii/p/11232535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!