题目描述
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.
样例输入
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
样例输出
Case #1: 14
Case #2: 63
思路
设 F(x) = M = k * e + z ;
A ^ F(x) = A ^ M = A ^ ( k * e + z )。即:M = k * e + z,e = M / k , z = M % k。(这里M范围是到1e9,这个 k 可以取1e5 )
A ^ F(x) mod P = A ^ ( 1e5 * e + z ) mod P = ( A ^ ( 1e5 * e ) * A ^ z ) mod P = (A ^ ( 1e5 * e ) mod P * ( A ^ z ) mod P ) mod P
分别用两个数组 fe [ e ] 和 fz [ z ] 来记录A ^ ( k * e ) mod P 和 A ^ z mod P,则又可得到:
A ^ F(x) = ( fe [ e ] * fz [ z ] ) mod P。
这里 e = F(x) / 1e5 , z = F(x) % 1e5
求出这两个数组,答案也就好求了(记得开long long)
求数组的过程还是看代码吧/(ㄒoㄒ)/~~
代码
#include<iostream>
#include<string>
#include<map>
#include<set>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<stack>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131
#define INF 0x3f3f3f3f
#define ls p<<1
#define rs p<<1|1
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps=1e-5;
const double pai=acos(-1.0);
const int N=1e5;
const int maxn=1e6+10;
ll t,n,A,K,a,b,m,P,fe[maxn],fz[maxn],f[maxn],tot;
void init()
{
fe[0]=fz[0]=1;
for(int i=1;i<=N;i++)
{
fz[i]=(A%P*fz[i-1])%P;
}
for(int i=1;i<=N;i++)
{
fe[i]=(fz[N]*fe[i-1])%P;
}
}
int main( )
{
scanf("%lld",&t);
while(t--)
{
ll ans=0;
scanf("%lld%lld%lld%lld%lld%lld%lld",&n,&A,&K,&a,&b,&m,&P);
init();
f[1]=K;
for(int i=2;i<=n;i++)
{
f[i]=(a*f[i-1]+b)%m;
}
for(int i=1;i<=n;i++)
{
ans=(ans+fe[f[i]/N]*fz[f[i]%N])%P;
}
printf("Case #%lld: %lld\n",++tot,ans);
}
return 0;
}
(唉,感觉题目好难啊,补题补的感觉自己要炸了/(ㄒoㄒ)/~~,菜是原罪,还得加油啊!!!)