51nod1242 斐波那契数列的第N项

来源:互联网 发布:中国农业部数据库 编辑:程序博客网 时间:2024/06/05 05:44
1242 斐波那契数列的第N项
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
 收藏
 关注
斐波那契数列的定义如下:

F(0) = 0
F(1) = 1
F(n) = F(n - 1) + F(n - 2) (n >= 2)

(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...)
给出n,求F(n),由于结果很大,输出F(n) % 1000000009的结果即可。
Input
输入1个数n(1 <= n <= 10^18)。
Output
输出F(n) % 1000000009的结果。
Input示例
11
Output示例

89

#include<cstdio>#include<iostream>#include<cstring>using namespace std;long long  ans[2][2],n;void fun(){    long long a[2][2]= {1,1,1,0},t[2][2]= {1,1,1,0};    ans[0][0]=ans[1][1]=1;    ans[0][1]=ans[1][0]=0;    while(n)    {        if(n&1)        {            memcpy(t,ans,sizeof(t));            memset(ans,0,sizeof(ans));            for(int i=0; i<2; i++)                for(int j=0; j<2; j++)                {                    for(int k=0; k<2; k++)                        ans[i][j]+=t[i][k]*a[k][j];                    ans[i][j]%=1000000009;                }        }        memcpy(t,a,sizeof(t));        memset(a,0,sizeof(a));        for(int i=0; i<2; i++)            for(int j=0; j<2; j++)            {                for(int k=0; k<2; k++)                    a[i][j]+=t[i][k]*t[k][j];                a[i][j]%=1000000009;            }        n>>=1;    }}int main(){    while(~scanf("%lld",&n)&&n>=0)    {        n--;        if(n>0)        {            fun();            printf("%lld\n",ans[0][0]);        }        else            printf("0\n");    }    return 0;}

#include<cstdio>#include<iostream>using namespace std;const long long M= 1000000009;long long f1,f2;long long n;int main(){    f1=1,f2=0;    long long a=1,b=1,c=1,d=0;    long long a1,b1,c1,d1;    cin>>n;    if(n==0)    {        cout<<0<<endl;        return 0;    }    n--;    while(n)    {        if(n&1)        {            long long t1=f1,t2=f2;            f1=(a*t1%M+b*t2%M)%M;            f2=(t1*c%M+d*t2%M)%M;        }        a1=a,b1=b,c1=c,d1=d;        a=a1*a1%M+b1*c1%M,b=a1*b1%M+b1*d1%M,c=a1*c1%M+c1*d1%M,d=b1*c1%M+d1*d1%M;        a%=M,b%=M,c%=M,d%=M;        n>>=1;    }    cout<<f1<<endl;    return 0;}


阅读全文
1 0
原创粉丝点击