洛谷 P1306斐波那契公约数

n,m<1e9 求gcd(f[n],f[m])

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

这就转化成矩阵快速幂求f[x];

性质2 gcd(f[n],f[n+1]) = 1;

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(v) v.begin(),v.end()
#define mem(a) memset(a,0,sizeof(a))


const ll mod =1e8;
const int N = 20;

//提议 : 求 gcd(f[n],f[m])  = f[gcd(n,m)]  tip: gcd(f[n],f[n+])=1;
namespace Matrix{
    int xn;
    struct Mat{
        int v[N][N];
        Mat(){}
        Mat(int x){
            memset(v,0,sizeof v);
            for (int i=1;i<=xn;i++)
                v[i][i]=x;
        }
        void Print(){
            for (int i=1;i<=xn;i++,puts(""))
                for (int j=1;j<=xn;j++)
                    printf("%3d ",v[i][j]);
            puts("");
        }
    };

    Mat operator * (Mat A,Mat B){
        Mat C(0);
        for (int i=1;i<=xn;i++)
            for (int j=1;j<=xn;j++)
                for (int k=1;k<=xn;k++)
                    C.v[i][j]=(1LL*A.v[i][k]*B.v[k][j]+C.v[i][j])%mod;
        return C;
    }
    Mat Pow(Mat x,ll y){
        Mat ans(1);
        for (;y;y>>=1,x=x*x)
            if (y&1ll){
                 ans=ans*x;
                 //ans.Print();
            }

        return ans;
    }
}
using namespace Matrix;
int main(){
    int n,m;
    cin>>n>>m;
    int v= __gcd(n,m);
    xn  = 2;
    Mat a;
    a.v[1][1]= a.v[1][2]= a.v[2][1]= 1;
    a.v[2][2]=0;

    Mat ans = Pow(a,1ll*v);

    cout<<ans.v[1][2]<<endl;


    return 0;
}

 

posted on 2019-04-25 17:38  Helpp  阅读(136)  评论(0编辑  收藏  举报

导航