You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
749 B

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
const int N = 3;
int n, mod;
// 矩阵乘法
void mul(int a[][N], int b[][N], int c[][N]) {
int t[N][N] = {0};
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
t[i][j] = (t[i][j] + (a[i][k] * b[k][j]) % mod) % mod;
}
memcpy(c, t, sizeof t);
}
signed main() {
int b[N][N] = {1, 1, 1};
int m[N][N] = {
{1, 0, 0},
{1, 1, 1},
{0, 1, 0}};
cin >> n >> mod;
// 矩阵快速幂
for (int i = n - 1; i; i >>= 1) {
if (i & 1) mul(b, m, b);
mul(m, m, m);
}
printf("%d\n", b[0][0]);
}