问题 C: A^X mod P
时间限制: 5 Sec 内存限制: 128 MB
题目描述
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.
样例输入 Copy
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
样例输出 Copy
Case #1: 14
Case #2: 63
一个比较显然的做法是直接每项快速幂,复杂度是
O
(
N
l
o
g
N
)
O(NlogN)
O(NlogN),卡常应该卡不过去,所以需要换一种做法。
怎么优化能过呢?显然需要去掉一个
l
o
g
log
log,这就需要
O
(
N
)
O(N)
O(N)的预处理了。
我们可以预处理出 A 的1 ~ 1e5 次幂,记录为数组a,让后再预处理出
A
1
e
5
A^{1e5}
A1e5 的 1 ~ 1e5 次幂,记录为数组b,显然这都是
O
(
N
)
O(N)
O(N)的。
让后考虑这样一个东西:
x
a
∗
x
b
=
x
a
+
b
x^a*x^b=x^ {a+b}
xa∗xb=xa+b
对于每个要求的A的次幂,假如是
A
1
e
6
+
10
A^{1e6+10}
A1e6+10,我们可以转换成
A
1
e
5
10
∗
A
10
A^{1e5^{10}}*A^{10}
A1e510∗A10 ,那么答案就是
a
[
10
]
∗
b
[
10
]
a[10]*b[10]
a[10]∗b[10] 。也就是说对于一个x次幂,答案就是
b
[
x
/
1
e
5
]
∗
a
[
x
m
o
d
1
e
5
]
b[x/1e5]*a[x \bmod1e5]
b[x/1e5]∗a[xmod1e5]。
还要注意一点就是 f [ 1 ] f[1] f[1]是不能%m的,因为这个我WA了十多发了。。
#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
#define R (u<<1|1)
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define pb push_back
#define mk make_pair
#define re register
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N=1000010,INF=0x3f3f3f3f,L=100000;
const double eps=1e-6;
LL pre[N],f[N],pre2[N];
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
int T=1;
int _; scanf("%d",&_);
while(_--)
{
printf("Case #%d: ",T++);
int n,A,k,a,b,m,p;
scanf("%d%d%d%d%d%d%d",&n,&A,&k,&a,&b,&m,&p);
f[1]=k; pre[0]=1; pre2[0]=1;
for(int i=2;i<=n;i++) f[i]=(1ll*a*f[i-1]+b)%m;
for(int i=1;i<=1e5;i++) pre[i]=1ll*pre[i-1]*A%p;
for(int i=1;i<=1e5;i++) pre2[i]=1ll*pre2[i-1]*pre[100000]%p;
LL ans=0;
for(int i=1;i<=n;i++)
{
int c=f[i];
if(c<=100000) ans=(1ll*ans+1ll*pre[c])%p;
else
{
int h=c/L,yu=c%L;
LL temp=(1ll*pre2[h]*pre[yu])%p;
ans=(1ll*ans+1ll*temp)%p;
}
}
printf("%lld\n",ans%p);
}
return 0;
}
/*
*/