A^X mod P
Time Limit: 5000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
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.
输入
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
输出
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.
示例输入
23 2 1 1 1 100 1003 15 123 2 3 1000 107
示例输出
Case #1: 14Case #2: 63 一开始直接用快速幂求的,/TLE了无限次后还是没解决,百度了一下,发现,直接讲f[i]分解为k×n+c的形式,记录下来,空间换时间,可以达到比较好的效果; 代码: #include <iostream> #include <stdio.h> #include <string.h> #include <algorithm> #include <stdlib.h> #include <string> #include <vector> #include <math.h> #include <stack> #include <map> #include <set> #include <queue> #define inf 0x3f3f3f3f #define Pi acos(-1.0) #define max(a,b) (a)>(b)?(a):(b) #define min(a,b) (a)>(b)?(b):(a) #define eps 1e-10 #define N 100000 using namespace std; typedef long long LL; int main() { int t; while(~scanf("%d",&t)) { int cnt=0; while(t--) { LL dp1[N+10];///存储A^(0)....A^(N) LL dp2[N+10];///存储A^(K*N)......A^(M) LL n,A,K,a,b,m,p; scanf("%lld%lld%lld%lld%lld%lld%lld",&n,&A,&K,&a,&b,&m,&p); dp1[0]=dp2[0]=1; dp1[1]=A%p; for(int i=2;i<=N;i++) { dp1[i]=(dp1[i-1]*dp1[1])%p; } dp2[1]=dp1[N]; for(int i=2;i<=100000;i++) { dp2[i]=(dp2[i-1]*dp2[1])%p; } LL f=K; LL ans=0; /// ans=f%p; for(int i=1;i<=n;i++) { ans+=(dp2[f/N]*dp1[f%N])%p;///组合分布求出答案; ans%=p; f=(a*f+b)%m; } printf("Case #%d: %lld\n",++cnt,ans); } } return 0; }