1. 程式人生 > >[斐波那契 數學技巧] 洛谷 P1306 斐波那契公約數

[斐波那契 數學技巧] 洛谷 P1306 斐波那契公約數

gcd(fib[n],fib[m])==fib[gcd(n,m)];

#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;

namespace F{  
  struct Matrix{  
    ll a,b,c,d;  
    Matrix(ll a=0,ll b=0,ll c=0,ll d=0):a(a),b(b),c(c),d(d) { }  
  };  
  inline Matrix Mul(Matrix A,Matrix B,ll p){  
    return Matrix((A.a*B.a+A.b*B.c)%p,(A.a*B.b+A.b*B.d)%p,(A.c*B.a+A.d*B.c)%p,(A.c*B.b+A.d*B.d)%p);    
  }  
  inline Matrix Pow(Matrix a,ll b,ll p){  
    Matrix ret(1,0,0,1);  
    for (;b;b>>=1,a=Mul(a,a,p))  
      if (b&1)  
    ret=Mul(ret,a,p);  
    return ret;  
  }  
  inline ll f(ll n,ll p){  
    if (!n) return 0;  
    return Pow(Matrix(1,1,1,0),n-1,p).a;  
  }  
}

int main(){
  int n,m;
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  scanf("%d%d",&n,&m);
  n=__gcd(n,m);
  printf("%lld\n",F::f((ll)n,100000000LL));
  return 0;
}