立志用最少的代码做最高效的表达
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 ) ) m o d u l a r P . ( A^{f(1)} + A^{f(2)} + A^{f(3)}+ ...... + A^{f(n)} ) modular P. (Af(1)+Af(2)+Af(3)+......+Af(n))modularP.
Input
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
Output
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.
Sample Input
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
Sample Output
Case #1: 14
Case #2: 63
分析
1e9的规模,即使O(n)的复杂度也没办法通过,因此考虑将指数分解
把指数 f(x) 分解为 f ( x ) = a k + b f(x) = ak+b f(x)=ak+b,这样一来, A f ( x ) = A a k ∗ A b A^{f(x)} = A^{ak} * A^b Af(x)=Aak∗Ab。
上式中的 k 和要打的表的大小有关,哪表开多大合适呢?理论上开 33333 就可以了,因为 sqrt(1e9) = 33333。这样只要计算 ( A 1 ) % P 、 ( A 2 ) % P … … ( A 33333 ) % P (A^1)\%P 、(A^2)\%P …… (A^{33333})\%P (A1)%P、(A2)%P……(A33333)%P 以及 ( A 1 ∗ 33333 ) % P ( A 2 ∗ 33333 ) % P … … ( A 33333 ∗ 33333 ) % P (A^{1*33333})\%P (A^{2*33333})\%P ……(A^{33333*33333})\%P (A1∗33333)%P(A2∗33333)%P……(A33333∗33333)%P ,对于 A f ( x ) A^{f(x)} Af(x),我们就可以通过上面两个数组相乘的结果得到了。
注意:
由于代码中涉及到乘法运算,所以 int 型会溢出,可以全部开 long long。
#include<bits/stdc++.h>
#define len 35000
using namespace std;
typedef long long gg;
gg n, A, K, a, b, m, P;
gg dp1[len + 10], dp2[len + 10];
void init() {
gg i;
dp1[0] = dp2[0] = 1;
for(i = 1; i <= len; i++)
dp1[i] = (dp1[i-1]*A)%P;
dp2[1] = dp1[len];
for(i = 2; i <= len; i++)
dp2[i] = (dp2[i-1]*dp2[1])%P;
}
int main() {
gg T; cin >> T;
for(gg j = 1; j <= T; j++){
cin >> n >> A >> K >> a >> b >> m >> P;
init();
gg ans = 0;
for(gg i = 1; i <= n; i++) {
ans = (ans + (dp1[K%len]*dp2[K/len])%P)%P;
K = (a * K + b) % m;
}
printf("Case #%lld: %lld\n", j, ans);
}
return 0;
}