A^X mod PIt's easy for ACMer to calculate A^X mod P. Now given seven integers n, A, K, a, b, m, P, and a function f(x) which defined as following.f(x) = K, x = 1f(x) = (a*f(x-1) + b)%m , x > 1Now, Your task is to calculate( A^(f(1)) + A^(f(2)) + A^(f(3)) + ...... + A^(f(n)) ) modular P.输入In the first line there is an integer T (1 < T <= 40), which indicates the number of test cases, and then T test cases follow. A test case contains seven integers n, A, K, a, b, m, P in one line.1 <= n <= 10^60 <= A, K, a, b <= 10^91 <= m, P <= 10^9输出For each case, the output format is “Case #c: ans”.c is the case number start from 1.ans is the answer of this problem.有C语音
时间: 2024-04-17 17:26:13 浏览: 108
非常抱歉,我之前的回答是基于Python的。以下是等效的C语言实现:
```c
#include <stdio.h>
unsigned long long pow_mod(unsigned long long base, unsigned long long exponent, unsigned long long modulus) {
unsigned long long result = 1;
base %= modulus;
while (exponent > 0) {
if (exponent % 2 == 1)
result = (result * base) % modulus;
base = (base * base) % modulus;
exponent /= 2;
}
return result;
}
unsigned long long calculate_expression(unsigned long long n, unsigned long long A, unsigned long long K, unsigned long long a, unsigned long long b, unsigned long long m, unsigned long long P) {
// 计算函数f(x)的值
unsigned long long f[n+1];
f[1] = K;
for (unsigned long long x = 2; x <= n; x++) {
f[x] = (a*f[x-1] + b) % m;
}
// 计算表达式的结果
unsigned long long result = 0;
for (unsigned long long x = 1; x <= n; x++) {
result += pow_mod(A, f[x], P);
result %= P;
}
return result;
}
int main() {
unsigned int T;
scanf("%u", &T);
for (unsigned int case_num = 1; case_num <= T; case_num++) {
unsigned long long n, A, K, a, b, m, P;
scanf("%llu %llu %llu %llu %llu %llu %llu", &n, &A, &K, &a, &b, &m, &P);
unsigned long long ans = calculate_expression(n, A, K, a, b, m, P);
printf("Case #%u: %llu\n", case_num, ans);
}
return 0;
}
```
请注意,此代码假设输入的整数不会超出unsigned long long类型的范围。如果您的输入可能超出该范围,请相应地更改数据类型。
希望这个C语言实现对您有所帮助!如果您还有其他问题,请随时提问。
阅读全文