A^X mod P

题目链接:http://acm.upc.edu.cn/problem.php?id=2219

2219: A^X mod P

Time Limit: 5 Sec  Memory Limit: 128 MB
Submit: 142  Solved: 28
[ Submit][ Status][ Web Board]

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
思路:刚看到这题想法是快速幂,但是仔细看了之后发现会超时,快速幂计算一个比较快,如果计算多个就没有这么快了;

那么我们的做法是预处理(打表)来降低时间复杂度;

f(x)最大不超过1e9;现打表出 A^1 mod p, A^2 mod p...........A^50000 mod p;

                                    再打表出 (A^50000)^1%p  (A^50000)^2%p  (A^50000)^3%p....  (A^50000)^50000%p 

然后查表就A了;

#include <iostream> 
#include <stdio.h> 
#include <string> 
#include <string.h> 
#include <algorithm> 
const int N=1e6+100; 
using namespace std; 
typedef long long ll; 
  
ll f[N]; 
ll X[500005]; 
ll Y[500005]; 
  
int main() 
{ 
   int T,test=1; 
   cin>>T; 
   while(T--) 
   { 
     ll n,A,K,a,b,m,p; 
     ll cnt=0; 
     cin>>n>>A>>K>>a>>b>>m>>p; 
    // a%=m,b%=m; 
  
     f[1]=K; 
     for(int i=2;i<=n;i++) 
        f[i]=(((a%m)*(f[i-1]%m))%m+b%m)%m; 
  
     X[0]=1; 
     for(int i=1;i<=50000;i++)X[i]=(A%p*X[i-1])%p; 
  
  
     Y[0]=1; 
     for(int i=1;i<=50000;i++)Y[i]=(X[50000]%p*Y[i-1]%p)%p; 
  
     for(int i=1;i<=n;i++) 
     { 
       cnt+=Y[f[i]/50000]*X[f[i]%50000]; 
       cnt%=p; 
     } 
     cout<<"Case #"<<test++<<": "; 
     cout<<cnt<<endl; 
  
   } 
   return 0; 
} 
  
/************************************************************** 
    Problem: 2219 
    User: liusuangeng 
    Language: C++ 
    Result: Accepted 
    Time:3032 ms 
    Memory:16892 kb 
****************************************************************/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值