初学矩阵快速幂,求条
查看原帖
初学矩阵快速幂,求条
1069308
lzy120406楼主2025/7/3 09:25

10pts

#include <bits/stdc++.h>
#define ll long long
#define db(s,a) cout << s << ":" << a << endl
#define dbarr(a,n) for(ll i=1;i<=n;i++) cout << a[i] << " " ; cout << endl ;
#define isok cout << "ok" << endl
using namespace std ;
const ll MAXN = 100005 ;
ll p , q , n , m , a1 , a2 ;
void matrix_mult(long long a[2][2], long long b[2][2], long long res[2][2]) {
	long long temp[2][2] = {0};
	for (int i = 0; i < 2; ++i) {
		for (int j = 0; j < 2; ++j) {
			for (int k = 0; k < 2; ++k) {
				temp[i][j] = (temp[i][j] + (a[i][k]%m) * (b[k][j]%m)) % m;
			}
		}
	}
	for (int i = 0; i < 2; ++i) {
		for (int j = 0; j < 2; ++j) {
			res[i][j] = temp[i][j];
		}
	}
}
void matrix_pow(long long a[2][2], long long n, long long res[2][2]) {
	long long temp[2][2] = {{a2, a1},{0, 0}};
	while (n > 0) {
		if (n & 1) {
			matrix_mult(temp, a, temp);
		}
		matrix_mult(a, a, a);
		n >>= 1;
	}
	for (int i = 0; i < 2; ++i) {
		for (int j = 0; j < 2; ++j){
			res[i][j] = temp[i][j] ;
		}
	}
}
long long fibonacci(long long n){
	if (n == -1) return a1 ;
	if (n == 0) return a2 ;
	long long a[2][2] = {{p,1}, {q,0}} ;
	long long res[2][2] ;
	matrix_pow(a,n-1,res) ;
	return res[0][0] ;
}
int main(){
//	freopen(".in","r",stdin) ;
//	freopen(".out","w",stdout) ;
	ios::sync_with_stdio(false) ;
	cin.tie(0) ;
	cout.tie(0) ;
	cin >> p >> q >> a1 >> a2 >> n >> m ;
	long long result = fibonacci(n-2);
	cout << result%m ;
	return 0 ;
}
2025/7/3 09:25
加载中...