Description
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.
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
Output
Case #1: 14
Case #2: 63
Hint
Source
附上一段会T的代码:
#include <stdio.h> #include <vector> #include <string.h> #include <iostream> #include <algorithm> #include <queue> using namespace std; #define ll long long const int inf = 0xffffff; const int maxn = 1e6+8; int n, t; ll A, K, a, b, m, P, f[maxn], fi[maxn]; ll qsm(ll x, ll y, ll z) { ll ans = 1; while(y) { if(y&1) { ans = ans*x%z; } x = x*x%z; y >>= 1; } return ans; } int main() { scanf("%d", &t); int ga = t; while(t--) { ll sum; scanf("%d%lld%lld%lld%lld%lld%lld", &n, &A, &K, &a, &b, &m, &P); ll miao = K;//存下第一项,f(x) = k sum = qsm(A, K, P);//存下第一项 A^(f(1))%P for(int i = 1; i<n; i++) { miao = (a*miao+b)%m;//由题可知,后一项等于 a*前一项+b,这里是依次算出以后的每一个f(i) sum = (sum+qsm(A, miao, P))%P;//这里是依次算出A^(f(i))%P } printf("Case #%d: %lld ", ga-t, sum); } return 0; }