C
来源:互联网 发布:百度知道和知乎 编辑:程序博客网 时间:2024/06/07 12:30
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
思路:
f(x)分解成f(x)=q*x+j;所以A^f(x)=(A^x)^q*A^j;
即将f(x)的值分段存,即A^f(x)分段存(将A^f(x)分为每段长为33333的33333段,求A^f(x)时先求在哪一段里面,再求这一段里面具体哪个位置。
#include<iostream>#include<string.h>#include<algorithm>using namespace std;#define maxn 33333long long x[2*maxn],y[2*maxn];long long n,A,K,a,b,m,p;void init(){ x[0]=1; for(int i=1;i<=maxn;i++){ x[i]=(x[i-1]*A)%p; } long long temp=x[maxn]; y[0]=1; for(int i=1;i<=maxn;i++){ y[i]=(y[i-1]*temp)%p; }}void solve(int tx){ long long fx=K; long long ans=0; for(int i=1;i<=n;i++){ ans=(ans+(y[fx/maxn]*x[fx%maxn])%p)%p; fx=(a*fx+b)%m; } cout<<"Case #"<<tx<<": "<<ans<<endl;}int main (){ int t; cin>>t; for(int l=1;l<=t;l++){ cin>>n>>A>>K>>a>>b>>m>>p; init(); solve(l); }}
0 0