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

 
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int mod = 1e9 + 9;

long long n;

struct Matrix{
    long long v[2][2];
};

Matrix Matrix_mul(Matrix a,Matrix b)
{
    Matrix ans;
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j < 2; j++)
        {
            ans.v[i][j] = 0;
            for(int k = 0; k < 2; k++)
            {
                ans.v[i][j] += (a.v[i][k]*b.v[k][j])%mod;
            }
            ans.v[i][j] = ans.v[i][j]%mod;
        }
    }
    return ans;
}

Matrix Matrix_pow(Matrix a,long long n)
{
    Matrix ans = {1,0,0,1};
    while(n)
    {
        if(n&1)
        {
            ans = Matrix_mul(ans,a);
        }
        n >>= 1;
        a = Matrix_mul(a,a);
    }
    return ans;
}

int main()
{
    while(~scanf("%lld",&n))
    {
        if(n==1)
        {
        	printf("1\n");
        	continue;
		}
        else
        {
            Matrix term1 = {1,1,1,0};
            Matrix term2 = {1,0,1,0};
            Matrix res = Matrix_pow(term1,n - 2);
            res = Matrix_mul(res,term2);
            printf("%lld\n",res.v[0][0]);
        }
    }
    return 0;
}  

猜你喜欢

转载自blog.csdn.net/love20165104027/article/details/81450731