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
23 2 1 1 1 100 1003 15 123 2 3 1000 107
Sample Output
Case #1: 14
Case #2: 63
本题目的关键在于大幂的分解和。因为不停的求A的幂,所以肯定把算过的保存下来最合适。那就是要打表。
把f分解为 fix * k + j 的形式,f就是f(x)的简称。然后关键是fix怎么整,多少合适。我觉得33333合适。
因为10^9 / 33333 =30000数组不大。然后余数也在33333之内。
然后就用普通的幂模相乘打表就可以f[i] = (f[i-1] * a)mod
#include <iostream>
using namespace std;
long long dp1[33333],dp2[33333];
//dp1中存的是A^1%P.......A^33333%P
//dp2中存的是A^(1*33333)%P A^(2*33333)%P A^(3*33333)%P........A^(33333*33333)%P
void F(long long A,long long P)
{
dp1[0]=dp2[0]=1;
for(int i=1;i<=33333;i++)
dp1[i]=(dp1[i-1]*A)%P;
dp2[1]=dp1[33333];
for(int i=2;i<=33333;i++)
dp2[i]=(dp2[i-1]*dp1[33333])%P;
}
int solve(long long n,long long A,long long K,long long a,long long b,long long m,long long P)
{
F(A,P);
long long ans=0,t=K;
for(int i=1;i<=n;i++)
{
ans=(ans%P+(dp2[t/33333]*dp1[t%33333])%P)%P;
t=(a*t+b)%m;
}
return ans;
}
int main()
{
int T,cases=1;
cin>>T;
while(T--)
{
long long n,A,K,a,b,m,P;
cin>>n>>A>>K>>a>>b>>m>>P;
cout<<"Case #"<<cases++<<": ";
cout<<solve(n,A,K,a,b,m,P)<<endl;
}
return 0;
}