A^X mod P
Time Limit: 5000 ms Memory Limit: 65536 KiB
Problem 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: 14Case #2: 63
Hint
运用预处理的两个数组进行O(1)的运算求出A^x (0<=x<=10^9)
dp1数组构造A^0~A^(10^5),间隔为A。
dp2数组构造A^(10^5)~A^(10^10),间隔为A^(10^5)。
这样对于任意的A^x就能表示成dp2[x/(10^5)]*dp1[x%(10^5)]
从而用空间换取时间。
代码:
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const ll maxn = 1e5;
ll n,A,K,a,b,m,p;
ll dp1[150000];
ll dp2[150000];
void init()//打表
{
dp1[0]= dp2[0] = 1;
dp1[1] = A%p;
for(int i = 2; i<=maxn ;i++)//构造A^0~A^(10^5),间隔为A
{
dp1[i] = (dp1[i-1]*dp1[1])%p;//(a * b) % p = (a % p * b % p) % p
}
dp2[1] = dp1[maxn];
for(int i = 2 ; i <=maxn; i++)//构造A^(10^5)~A^(10^10),间隔为A^(10^5)。
{
dp2[i] = (dp2[i-1]*dp2[1])%p;
}
}
int main()
{
int t ;
scanf("%d",&t);
for(int ans = 1; ans <=t ;ans++)
{
scanf("%lld%lld%lld%lld%lld%lld%lld",&n,&A,&K,&a,&b,&m,&p);
init();
ll res = 0;
ll f = K;
for(int i = 1; i <= n ;i++)
{
res = (res+dp2[f/maxn]*dp1[f%maxn])%p;
f = (a*f + b)%m;
}
printf("Case #%d: %lld\n",ans,res);
}
return 0;
}