题目描述
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.
样例输入
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
样例输出
Case #1: 14
Case #2: 63
解决思路
打表出奇迹!!!
打表
f
:
A
0
A
1
A
2
.
.
.
.
.
.
A
1
e
5
\small f:A^0 A^1 A^2......~A^{1e5}
f:A0A1A2...... A1e5
打表
g
:
A
0
A
1
e
5
A
2
e
5
.
.
.
.
.
.
A
1
e
10
\small g:A^0 A^{1e5} A^{2e5}......~A^{1e10}
g:A0A1e5A2e5...... A1e10
所以
A
n
=
A
⌊
n
1
e
5
⌋
×
1
e
5
×
A
n
%
1
e
5
\small A^n = A^{\lfloor \frac{n}{1e5}\rfloor \times1e5} \times A^{n\% 1e5}
An=A⌊1e5n⌋×1e5×An%1e5
#include<stack>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
ll n, A, K, a, b, m, p;
ll f[N], g[N];
inline ll mod_m(ll n) { return n % m; }
inline ll mod_p(ll n) { return n % p; }
void init(const int n = 1e5) {
f[0] = g[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = mod_p(f[i - 1] * A);
}
g[1] = f[n];
for (int i = 1; i <= n; i++) {
g[i] = mod_p(g[i - 1] * g[1]);
}
}
int main() {
int T; cin >> T;
for (register int t = 1; t <= T; t++) {
cin >> n >> A >> K >> a >> b >> m >> p;
init();
ll ans = mod_p(f[K % 100000] * g[K / 100000]), sv = K;
for (register int i = 2; i <= n; i++) {
sv = mod_m(sv * a + b);
ans = mod_p(ans + mod_p(f[sv % 100000] * g[sv / 100000]));
}
printf("Case #%d: %lld\n", t, ans);
}
return 0;
}