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

51Nod - 1242 斐波那契(快速幂)

时间:2018-11-18 22:33:01      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:快速   stdio.h   put   \n   int   include   mes   while   ++   

斐波那契数列的定义如下:
 
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的结果。Sample Input

11

Sample Output

89



#include <iostream>
#include<string.h>
#include<stdio.h>
#define ll long long
using namespace std;
const ll mod = 1000000009;
struct mat
{
    ll m[2][2];
    mat()
    {
        memset(m, 0, sizeof(m));
    }
};
mat mul(mat &A, mat &B)
{
    mat C;
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            for (int k = 0; k < 2; k++) 
            {
                C.m[i][j] = (C.m[i][j] + A.m[i][k] * B.m[k][j]) % mod;
            }
        }
    }
    return C;
}
mat pow(mat A, ll n)
{
    mat B;
    B.m[0][0] = B.m[0][1] = 1;
    while (n)
    {
        if (n & 1)
            B = mul(A, B);
        A = mul(A, A);
        n >>= 1;
    }
    return B;
}
int main()
{
    ll n;
    while (cin >> n)
    {
        mat A;
        A.m[0][0] = A.m[0][1] = A.m[1][0] = 1;
        mat B = pow(A, n);
        printf("%lld\n", B.m[1][0]);
    }
    return 0;
}

 

51Nod - 1242 斐波那契(快速幂)

标签:快速   stdio.h   put   \n   int   include   mes   while   ++   

原文地址:https://www.cnblogs.com/-citywall123/p/9979663.html

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