求助,取模部分有问题
查看原帖
求助,取模部分有问题
1034295
QuaternaryTree楼主2024/7/23 17:14

rt

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#define int long long
using namespace std;

int p;

inline int read() {
	int x = 0, f = 1;
	char ch = getchar();
	while (ch < '0' || ch > '9') {
		if (ch == '-')
			f = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch <= '9') {
		x = (x << 1) + (x << 3) + (ch ^ 48);
		ch = getchar();
	}
	return x * f;
}

inline void write(int x) {
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}

int gcd(int a, int b) {
	while (a != b) {
		if (a > b) a -= b;
		else b -= a;
	}
	return a;
}

//const int mod = 1e9 + 7;
const int MAXN = 21;
const int QQ = 1e9 + 7;

int n, L =  2;

struct Matrix {
	int M[MAXN][MAXN];
	void clear() {
		memset(M, 0, sizeof(M));
	}
	void reset() {
		clear();
		for (int i = 0; i < L; ++i) M[i][i] = 1;
	}
	Matrix friend operator *(const Matrix &A, const Matrix &B) {
		Matrix Ans;
		Ans.clear();
		for (int i = 0; i < L; ++i)
			for (int j = 0; j < L; ++j)
				for (int k = 0; k < L; ++k)
					Ans.M[i][j] = (Ans.M[i][j] + A.M[i][k] * B.M[k][j]) % p;
		return Ans;
	}
} A, B;

Matrix expow(Matrix T, int P) {
	Matrix Ans;
	Ans.reset();
	while (P) {
		if (P & 1)
			Ans = Ans * T;
		T = T * T, P >>= 1;
	}
	return Ans;
}

signed main() {
	n = read(),p = read();
	const int mod = p;
	if (n <= 2) {
		int ans = 1;
		ans %= p;
		write(ans);
		return 0;
	}
	A.M[0][0] = 1;
	A.M[0][1] = 1;
	A.M[1][0] = 1;
	A.M[1][1] = 0;
	A = expow(A, n - 2);
	int ans = (A.M[0][0] + A.M[0][1]) % mod;
	write(ans);
	return 0;
}
2024/7/23 17:14
加载中...