Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P4000 斐波那契数列

P4000 斐波那契数列

有结论,斐波那契数列的循环节的上界为 $6p$ 。考虑矩阵加速,设斐波那契的第 $i$ 项和第 $i + 1$ 项构成的矩阵为 $A _ i$ ,转移矩阵为 $B$ 。如果有循环节 $k$ ,那么有 $A _ 1 B ^ k = A _ 1 \mod p$ 。$A, B$ 显然都是存在逆的,那么 $B ^ k = I$ ,其中 $I$ 表示单位矩阵。这样将问题转化为 BSGS 的标准形式。用 BSGS 可以在 $O(\sqrt p \log \sqrt p)$ 的时间内解得 $k$ 。然后直接矩阵加速即可。

查看代码
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <cstdio>
#include <cmath>
#include <array>
#include <map>
#include <cstring>
using namespace std;
template <class Type>
void read (Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0';
flag && (x = ~x + 1);
}
template <class Type, class ...rest>
void read (Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write (Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar('0' + x % 10);
}
const int N = 2, M = 3e7 + 10;
typedef long long LL;
typedef array<array<int, N>, N> Matrix;
int p;
Matrix operator * (const Matrix &a, const Matrix &b)
{
Matrix res;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
{
res[i][j] = 0;
for (int k = 0; k < N; ++k)
res[i][j] = (res[i][j] + (LL)a[i][k] * b[k][j]) % p;
}
return res;
}
Matrix binpow (Matrix b, LL k)
{
Matrix res;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = i == j;
for (; k; k >>= 1, b = b * b)
if (k & 1) res = res * b;
return res;
}
LL BSGS (Matrix A, Matrix B)
{
int k = sqrt(p * 6ll) + 1;
map <Matrix, int> H;
Matrix s = B;
for (int i = 0; i < k; ++i, s = s * A) H[s] = i;
Matrix t = binpow(A, k);
s = t;
for (int i = 1; i <= k; ++i, s = s * t)
if (H.count(s)) return (LL)i * k - H[s];
return -1;
}
char str[M];
int main ()
{
scanf("%s", str);
read(p);
Matrix A, B;
A[0][0] = A[0][1] = A[1][0] = 1, A[1][1] = 0;
B[0][0] = B[1][1] = 1, B[0][1] = B[1][0] = 0;
LL mod = BSGS(A, B);
int len = strlen(str);
LL n = 0;
for (int i = 0; i < len; ++i)
n = (n * 10ll + str[i] - '0') % mod;
write(binpow(A, n)[1][0]);
return 0;
}