问题 C: A^X mod P
时间限制: 5 Sec 内存限制: 128 MB
题目描述
It’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 = 1
f(x) = (a*f(x-1) + b)%m , x > 1
Now, 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^6
0 <= A, K, a, b <= 10^9
1 <= 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.
样例输入 Copy
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
样例输出 Copy
Case #1: 14
Case #2: 63
本体做法:大幂分解求法
就像9 = 2 * 4 + 1
一样,任何一个很大的数T
可以写成T = a * N + b;
其中,N
为一个任意的比较大的数
这题就是依靠的这样的一个思想。
// 大幂分解求和
#include <iostream>
using namespace std;
typedef long long ll;
const int N = 1e6 + 10;
int t, cnt;
ll s1[N], s2[N];
int main(){
scanf("%d", &t);
while (t -- ){
cnt ++;
int n, A, k, a, b, m, p;
scanf("%d%d%d%d%d%d%d", &n, &A, &k, &a, &b, &m, &p);
s1[0] = s2[0] = 1;
for (int i = 1; i < N; i ++ ) s1[i] = s1[i - 1] * A % p;//余数部分`b`
ll v = s1[N - 1];//N为这里的v
for (int i = 1; i < N; i ++ ) s2[i] = s2[i - 1] * v % p;//整除部分`a`
ll f = k, res = 0;
for (int i = 1; i <= n; i ++ ){
res = (res % p + s2[f / (N - 1)] % p * s1[f % (N - 1)] % p) % p;
f = (a * f % m + b) % m;
}
printf("Case #%d: %lld\n", cnt, res);
}
return 0;
}