码迷,mamicode.com
首页 > 其他好文 > 详细

51nod 1242 斐波那契数列的第N项(矩阵快速幂)

时间:2015-08-27 18:51:42      阅读:707      评论:0      收藏:0      [点我收藏+]

标签:

基准时间限制: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<iostream>
#include<algorithm>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define mod 1000000009

using namespace std;

long long int n;

struct node {
    long long int c[2][2];
} t;

node mult(node a,node b) {   ///矩阵相乘
    node cc;
    for(int i=0; i<2; i++) {
        for(int j=0; j<2; j++) {
            cc.c[i][j] = 0;
            for(int k=0; k<2; k++) {
                cc.c[i][j] += (a.c[i][k]*b.c[k][j])%mod;
            }
            cc.c[i][j] = cc.c[i][j]%mod;
        }
    }
    return cc;
}

node expo(long long int nn) {
    node pt = t;
    if(nn<0){
        return pt;
    }
    while(nn) {
        if(nn&1) {
            pt = mult(pt,t);
            nn--;
        }
        t = mult(t,t);
        nn = nn>>1;
    }
    return pt;
}

int main() {
    while(scanf("%lld",&n)!=EOF) {
        t.c[0][0] = 1;
        t.c[0][1] = 1;
        t.c[1][0] = 1;
        t.c[1][1] = 0;
        node tt = expo(n-2);
        printf("%lld\n",tt.c[0][0]);
    }
    return 0;
}


版权声明:本文为博主原创文章,如有特殊需要请与博主联系 QQ : 793977586。

51nod 1242 斐波那契数列的第N项(矩阵快速幂)

标签:

原文地址:http://blog.csdn.net/yeguxin/article/details/48029931

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!