您的位置:首页 > 其它

斐波那契数列的第N项 矩阵快速幂

2016-10-29 21:14 274 查看
斐波那契数列的定义如下:

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<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
#define ll long long
#define mod 1000000009
struct node
{
ll c[2][2];
}f;
node multi(node a, node b);
node ksm(ll n);
int main()
{
int i, j, k, sum;ll n;
while (~scanf("%lld", &n))
{
f.c[0][0] = 1;
f.c[0][1] = 1;
f.c[1][0] = 1;
f.c[1][1] = 0;
node temp = ksm(n - 2);
printf("%lld\n", temp.c[0][0]);
}
return 0;
}
node ksm(ll n)
{
node x = f;
if (n < 0)
return x;
while (n)
{
if (n % 2 == 1)
{
x = multi(x, f);
n--;
}
f = multi(f, f);
n /= 2;
}
return x;
}
node multi(node a, node b)
{
node x = { 0 };
for (int i = 0;i < 2;i++)
{
for (int j = 0;j < 2;j++)
{
for (int k = 0;k < 2;k++)
{
x.c[i][j] += (a.c[i][k] * b.c[k][j]);
x.c[i][j] %= mod;
}
}
}
return x;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: