Problem 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.
Example Input
23 2 1 1 1 100 1003 15 123 2 3 1000 107
Example Output
Case #1: 14Case #2: 63
思路:分解打表,将A^f中的 f分解为 i * k + j的形式 。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <stack>
#define LL long long
#define INF 0x7fffffff
#define maxn 33333
#define PI 3.1415926535897932
#define E 2.718281828459045
using namespace std;
long long t,n,A,K,a,b,m,p;
long long X[maxn+10],Y[maxn+10];
void init() //打表;
{
int i;
X[0]=1;
for(i=1;i<=maxn;i++){
X[i]=(X[i-1]*A)%p;
}
Y[0]=1;
long long ans=X[maxn];
for(i=1;i<=maxn;i++){
Y[i]=(Y[i-1]*ans)%p;
}
}
int main()
{
int cases=1;
scanf("%d",&t);
while(t--)
{
scanf("%I64d%I64d%I64d%I64d%I64d%I64d%I64d",&n,&A,&K,&a,&b,&m,&p);
init();
long long sum=0;
for(long long i=1;i<=n;i++){
sum=(sum+(X[K%maxn]*Y[K/maxn])%p)%p; //把K分解成(K/maxn)*maxn+(K%maxn);
K=(a*K+b)%m;
}
cout<<"Case #"<<cases<<": "<<sum<<endl;
cases++;
}
return 0;
}