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


矩阵快速幂

/*
    data:2018.5.13
    author:gsw
    link:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1242
*/
#define ll long long
#define IO ios_with_sync(false);

#include<iostream>
#include<algorithm>
#include<math.h>
#include<stdio.h>
#include<string.h>
using namespace std;

ll mod=1000000009;
class Matrix
{
    public:
        ll matrix[2][2];
};
Matrix a,b,ans;

void init()
{
    a.matrix[0][0]=1;a.matrix[0][1]=1;a.matrix[1][0]=1;a.matrix[1][1]=0;
    b.matrix[0][0]=1;b.matrix[0][1]=0;b.matrix[1][0]=0;b.matrix[1][1]=0;
    memset(ans.matrix,0,sizeof(ans.matrix));
    ans.matrix[0][0]=1;ans.matrix[1][1]=1;
}
Matrix mul(Matrix a1,Matrix a2)
{
    Matrix ans;
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            ans.matrix[i][j] = 0;
            for(int k = 0 ; k <2; k++)
            {
                ans.matrix[i][j] +=a1.matrix[i][k]*a2.matrix[k][j]%mod;
                ans.matrix[i][j]%=mod;
            }
        }
    }
    return ans;
}
void fast_mod(ll n)
{
    while (n>0)
    {
        if(n&1)ans=mul(ans,a);
        a=mul(a,a);
        n=n>>1;
    }
}

int main()
{
    ll n;
    scanf("%lld",&n);
    init();
    fast_mod(n-1);
    b=mul(b,ans);
    cout<<b.matrix[0][0]<<endl;
    //main();
}

猜你喜欢

转载自www.cnblogs.com/fantastic123/p/9033521.html
今日推荐