zoukankan      html  css  js  c++  java
  • 洛谷 P1306 斐波那契公约数

    题目描述

    对于Fibonacci数列:1,1,2,3,5,8,13......大家应该很熟悉吧~~~但是现在有一个很“简单”问题:第n项和第m项的最大公约数是多少?

    输入输出格式

    输入格式:

     

    两个正整数n和m。(n,m<=10^9)

    注意:数据很大

     

    输出格式:

     

    Fn和Fm的最大公约数。

    由于看了大数字就头晕,所以只要输出最后的8位数字就可以了。

     

    输入输出样例

    输入样例#1:
    4 7
    输出样例#1:
    1

    说明

    用递归&递推会超时

    用通项公式也会超时

    思路:gcd(f(n),f(m))=f(gcd(n,m)),+矩阵乘法加速斐波那契。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    #include<ctime>
    #include<cstdlib>
    #define maxn 3
    #define mod 100000000
    using namespace std;
    long long n,m,gcd,a[maxn][maxn],ans[maxn][maxn],tmp[maxn][maxn];
    void mi(long long s1[maxn][maxn],long long s2[maxn][maxn]){
        memset(tmp,0,sizeof(tmp));
        for(int i=1;i<=2;i++)
            for(int j=1;j<=2;j++)
                for(int k=1;k<=2;k++)
                    tmp[i][j]=(tmp[i][j]+s1[i][k]*s2[k][j])%mod;
        for(int i=1;i<=2;i++)
            for(int j=1;j<=2;j++)
                s1[i][j]=tmp[i][j]; 
    }
    void work(){
        while(n){
            if(n&1)
                mi(ans,a);
            n=n/2;
            mi(a,a);
        }
        cout<<ans[1][1]<<endl;
    }
    long long GCD(long long x,long long y){
        return x==0?y:GCD(y%x,x);
    } 
    int main(){
        //freopen("spfa.in","r",stdin);
        //freopen("spfa.out","w",stdout);
        cin>>n>>m;
        gcd=GCD(n,m);
        gcd-=2;
        if(gcd<=0){
            cout<<"1";
            return 0;
        }
        n=gcd;
        a[1][1]=1;a[1][2]=1;
        a[2][1]=1;a[2][2]=0;
        ans[1][1]=1;ans[1][2]=1;
        ans[2][1]=1;ans[2][2]=0;
        work();
    }
    细雨斜风作晓寒。淡烟疏柳媚晴滩。入淮清洛渐漫漫。 雪沫乳花浮午盏,蓼茸蒿笋试春盘。人间有味是清欢。
  • 相关阅读:
    Python Django开发遇到的坑(版本不匹配)
    Mysql安装与问题合集
    git branch -r查看不了远程所有分支
    angularJS使用$http请求下载excel表格
    遍历formData对象数据
    按需使用CryptoJS之AES加密(CFB)模式
    git之创建、删除分支
    git pull时报错:Access Denied (拒绝访问)
    angularJS监听数据变化
    Angular-ui-router入门
  • 原文地址:https://www.cnblogs.com/cangT-Tlan/p/7510061.html
Copyright © 2011-2022 走看看