【简单数论】H - A^X mod P_HRBUST - 2049_31行代码AC
立志用最少的代碼做最高效的表達
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
(Af(1)+Af(2)+Af(3)+......+Af(n))modularP.( 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)=ak+bf(x) = ak+bf(x)=ak+b,這樣一來, Af(x)=Aak?AbA^{f(x)} = A^{ak} * A^bAf(x)=Aak?Ab。
上式中的 k 和要打的表的大小有關,哪表開多大合適呢?理論上開 33333 就可以了,因為 sqrt(1e9) = 33333。這樣只要計算 (A1)%P、(A2)%P……(A33333)%P(A^1)\%P 、(A^2)\%P …… (A^{33333})\%P(A1)%P、(A2)%P……(A33333)%P 以及 (A1?33333)%P(A2?33333)%P……(A33333?33333)%P(A^{1*33333})\%P (A^{2*33333})\%P ……(A^{33333*33333})\%P(A1?33333)%P(A2?33333)%P……(A33333?33333)%P ,對于 Af(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; }
總結
以上是生活随笔為你收集整理的【简单数论】H - A^X mod P_HRBUST - 2049_31行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1002 A+B for Polynom
- 下一篇: Thrall’s Dream HRBUS