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

斐波那契数列的定义如下:
 
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;
}

 

posted @ 2018-11-18 21:38  知道了呀~  阅读(180)  评论(0编辑  收藏  举报