斐波那契数列的第N项 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<=1018) n ( 1 <= n <= 10 1 8 ) 。
Output
输出 F(n)%1000000009 F ( n ) % 1000000009 的结果。
Sample Input
11
Sample Output
89
我的代码
#include <iostream>
using namespace std;
const long long int mod = 1000000009;
struct matrix
{
long long int m[2][2];
matrix()//赋初始值为0
{
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
{
m[i][j] = 0;
}
}
}
};
matrix mul(matrix A, matrix B)//矩阵相乘
{
matrix res;
for(int i = 0; i <2; i++)
{
for(int j = 0; j < 2; j++)
{
res.m[i][j] = 0;
for(int k = 0; k < 2; k++)
{
res.m[i][j] += A.m[i][k]*B.m[k][j]%mod;
}
}
}
return res;
}
matrix pow(matrix A, long long int n)//矩阵求幂
{
matrix imatrix;//单位矩阵
imatrix.m[0][0] = 1;
imatrix.m[1][1] = 1;
if(n == 0)
{
return imatrix;
}
if(n%2 == 0)
{
return pow(mul(A,A),n/2);
}
else
{
return mul(pow(mul(A,A),n/2),A);
}
}
int main()
{
matrix A,ans;
A.m[0][0] = 1;
A.m[0][1] = 1;
A.m[1][0] = 1;
ans.m[0][0] = 1;
long long int n;
while(cin>>n)
{
matrix B = mul(ans,pow(A,n-1));
cout << B.m[0][0] << endl;
}
return 0;
}