LuoGu P1306 Fibonacci

https://www.luogu.org/problemnew/show/P1306

这次遇见了我再具体数学那本书上看到的结论23333

当时WildCow学长还证出来了

两个Fibonacci Number 's Gcd=Gcd 's Fibonacci

Code of AC:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M=1e9;
ll modmul(ll a, ll b, ll n) {
    ll ans = 0;
    while(b) {
        if(b&1)    ans = (ans + a) % n;
        a = (a + a) % n;
        b >>= 1;
    }
    return ans;
}
void mul(ll f[2],ll a[2][2]){
    ll c[2];
    memset(c,0,sizeof c);
    for(ll j=0;j<2;++j)
        for(ll k=0;k<2;++k)
            c[j]=(c[j]+modmul(f[k],a[k][j],M))%M;
    memcpy(f,c,sizeof c);
}
void mulself(ll a[2][2]){
    ll c[2][2];
    memset(c,0,sizeof c);
    for(ll i=0;i<2;++i)
        for(ll j=0;j<2;++j)
            for(ll k=0;k<2;++k)
                c[i][j]=(c[i][j]+modmul(a[i][k],a[k][j],M))%M;
    memcpy(a,c,sizeof c);
}
ll Fi(ll x){
    ll f[2]={0,1};
    ll a[2][2]={{0,1},{1,1}};
    for(;x;x>>=1){
        if(x&1) mul(f,a);
        mulself(a);
    }
    return f[0];
}
int main(){
    ll x,y;
    cin>>x>>y;
    ll G=__gcd(x,y);
    cout<<Fi(G)<<endl;
}

猜你喜欢

转载自blog.csdn.net/gipsy_danger/article/details/80573581