题意:给出a,b,n,m按如下公式计算输出Sn
题解:和之前做过的一题很像,推导公式如下
(a+根号b)^n = xn + yn×根号b
–> (xn-1 + yn-1×根号b)×(a+根号b) = (a*xn-1 + b*yn-1) + (xn-1 + a×yn-1)×根号b
然后写成矩阵形式后
(a-根号b)^n = xn - yn×根号b
xn+yn×根号b = xn+yn×根号b + xn-yn×根号b - (xn-yn×根号b) = 2×xn + (a-根号b)
由于题目有给出范围(a-1)^n < b < a^n,所以 0 < a-根号b < 1,那么为了向上取整结果就是2*xn。
#include <stdio.h>
#include <string.h>
const int N = 3;
int a, b, n, m;
struct Mat {
int g[N][N];
}ori, res;
Mat multiply(Mat x, Mat y) {
Mat temp;
memset(temp.g, 0, sizeof(temp.g));
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
temp.g[i][j] = (temp.g[i][j] + x.g[i][k] * y.g[k][j]) % m;
return temp;
}
void calc(int n) {
while (n) {
if (n & 1)
res = multiply(ori, res);
n >>= 1;
ori = multiply(ori, ori);
}
}
int main() {
while (scanf("%d%d%d%d", &a, &b, &n, &m) == 4) {
memset(res.g, 0, sizeof(res.g));
ori.g[0][0] = ori.g[1][1] = a % m;
ori.g[0][1] = b % m;
ori.g[1][0] = 1;
res.g[0][0] = 1;
calc(n);
printf("%d\n", (2 * res.g[0][0]) % m);
}
return 0;
}
时间: 2024-10-10 05:38:53