斐波那契数列的第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
Output
Input示例
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;
}
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;
}
相关文章推荐
- 斐波那契数列的第N项(1≤n≤10^18 矩阵快速幂)
- 矩阵快速幂 求斐波拉切数列的第n项 poj3070
- 快速计算类似斐波那契数列数列的数列的第N项,矩阵快速幂
- HDU2256&&HDU4565:给一个式子的求第n项的矩阵快速幂
- poj 3070 Fibonacci (矩阵快速幂求斐波那契数列的第n项)
- <矩阵快速幂>codevs 3332 数列
- 矩阵乘法快速幂 codevs 1574 广义斐波那契数列
- 第八场多校联盟 Problem D: 数列问题 【矩阵快速幂】
- 【51Nod】1242 - 斐波那契数列的第N项(矩阵快速幂)
- 矩阵快速幂求斐波拉切数列
- pku 3070 Fibonacci 矩阵快速幂相乘求Fibonacci 数列
- 矩阵乘法 与 矩阵快速幂详解 以51NOD1242 斐波那契数列的第N项为例
- 矩阵快速幂1242斐波那契数列的第N项
- 【模拟试题】数列 矩阵快速幂
- POJ 3070(矩阵快速幂,求斐波那契第n项)
- 51nod 1126 求递推序列的第N项 矩阵快速幂
- 【矩阵快速幂】数列
- 51nod 1126 求递推序列的第N项(矩阵快速幂)
- [51NOD1126]求递推序列的第n项(矩阵快速幂)
- codevs 3332 数列(矩阵快速幂)