Fibonacci 前 n 项和

Description

大家都知道 Fibonacci 数列吧,$f_1=1,f_2=1,f_3=2,f_4=3,…,f_n=f_{n-1}+f_{n-2}$
现在问题很简单,输入 $n$ 和 $m$,求 ${f_n}$ 的前 $n$ 项和 $S_n \bmod m$.

Solution

一种方法是直接构造一个$3\times 3$的矩阵, 矩阵快速幂求解.还有一种方法是attack说的, $\sum_{i=1}^n=f_{n +2}-1$, 可以直接求斐波那契数列第$n+2$项.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <string.h>
#include <algorithm>
int mod;
struct Matrix {
long long m[3][3];
Matrix() { m[0][0] = m[0][1] = m[0][2] =
m[1][0] = m[1][1] = m[1][2] =
m[2][0] = m[2][1] = m[2][2] = 0; }
void init() { m[0][0] = m[1][1] = m[2][2] = 1; }
Matrix operator * (const Matrix& o) const {
Matrix r;
for (int i = 0; i < 3; i += 1)
for (int j = 0; j < 3; j += 1)
for (int k = 0; k < 3; k += 1)
r.m[i][j] += m[i][k] * o.m[k][j] % mod,
r.m[i][j] %= mod;
return r;
}
Matrix operator ^ (int b) {
Matrix res, base = *this;
res.init();
while (b) {
if (b & 1) res = res * base;
base = base * base;
b >>= 1;
}
return res;
}
};
int main () {
int n; scanf("%d%d", &n, &mod);
Matrix A;
A.m[0][0] = A.m[0][1] = A.m[1][1] = A.m[1][2] = A.m[2][1] = 1;
A = A ^ (n - 1);
long long res = 0;
res = A.m[0][0] + A.m[0][1] + A.m[0][2];
res %= mod;
printf("%d\n", res);
return 0;
}
-------------本文结束感谢您的阅读-------------