[矩阵乘法]斐波那契数列IV

[

]

I

V

[矩阵乘法]裴波拉契数列IV

[矩阵乘法]裴波拉契数列IV

Description

求数列f[n]=f[n-2]+f[n-1]+n+1的第N项,其中f[1]=1,f[2]:=1.


Input

n(1<n<231-1)


Output

一个数为裴波拉契数列的第n项mod 9973;


Sample Input

10000


Sample Output

4399


题目解析

对于为什么用矩阵乘法来做,详见博客斐波那契数列II

关于递推式略, 详见博客斐波那契数列III,并请独自尝试通过类比来推递推式。

然后可以构造出一个

4

4

4 * 4

4∗4的矩阵

T

T

T

0

1

0

0

1

1

0

0

0

1

1

0

0

1

1

1

\begin{vmatrix} 0 & 1 & 0 & 0\\ 1 & 1 & 0 & 0\\ 0 & 1 & 1 & 0\\ 0 & 1 & 1 & 1\\ \end{vmatrix}

∣∣∣∣∣∣∣∣​0100​1111​0011​0001​∣∣∣∣∣∣∣∣​


Code

#include <cmath>
#include <cstdio>
#include <iostream>
using namespace std; int nt;
const int MOD = 9973; struct matrix
{
int n, m;
int t[10][10];
}t1, t2, t3; matrix operator *(matrix t, matrix r)
{
matrix c;
c.n = t.n, c.m = r.m;
for (int i = 1; i <= c.n; ++ i)
for (int j = 1; j <= c.m; ++ j)
c.t[i][j]=0;
for (int k = 1; k <= t.m; ++ k)
for (int i = 1; i <= t.n; ++ i)
for (int j = 1; j <= r.m; ++ j)
c.t[i][j] = (c.t[i][j] + t.t[i][k] * r.t[k][j] % MOD) % MOD;
return c;
} void rt (int k)
{
if (k == 1)
{
t2 = t1;
return;
}
rt (k / 2);
t2 = t2 * t2;
if (k & 1) t2 = t2 * t1;
} int main()
{
scanf ("%d", &nt);
if (nt == 1)
{
printf ("1");
return 0;
}
t3.n = 1;
t1.n = t1.m = t3.m = 4;
t1.t[1][1] = 0, t1.t[1][2] = 1, t1.t[1][3] = 0, t1.t[1][4] = 0;
t1.t[2][1] = 1, t1.t[2][2] = 1, t1.t[2][3] = 0, t1.t[2][4] = 0;
t1.t[3][1] = 0, t1.t[3][2] = 1, t1.t[3][3] = 1, t1.t[3][4] = 0;
t1.t[4][1] = 0, t1.t[4][2] = 1, t1.t[4][3] = 1, t1.t[4][4] = 1;
t3.t[1][1] = t3.t[1][2] = t3.t[1][4] = 1; t3.t[1][3] = 3;
rt (nt - 1);
t3 = t3 * t2;
printf ("%d", t3.t[1][1]);
return 0;
}
上一篇:linux – 命令行音频 – 用于同时播放和录制的管道


下一篇:51nod 1031+斐波那契和杨辉三角的一些基础知识