upc.2219: A^X mod P(打表 && 超越快速幂(in some ways))

本文介绍了一种解决ACM竞赛中涉及大量快速幂运算问题的方法。通过将指数拆分为小数部分和大数部分,并预处理两种情况下的结果,实现了在O(1)的时间复杂度内快速求解。适用于指数范围为1到10^9的问题。

2219: A^X mod P

Time Limit: 5 Sec  Memory Limit: 128 MB Submit: 417  Solved: 68 [ 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

2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107

Sample Output

Case #1: 14
Case #2: 63

HINT

 

Source

2013年山东省第四届ACM大学生程序设计竞赛

 1 #include<stdio.h>
 2 typedef long long ll ;
 3 int T ;
 4 int  n, A, K, a, b, m, P ;
 5 int small [1 << 15 | 5] ;
 6 int big [1 << 15 | 5] ;
 7 int ans ;
 8 
 9 void solve ()
10 {
11     int ret = 0 ;
12     small[0] = 1 % P ;
13     for (int i = 1 ; i < (1 << 15 | 5) ; i++) {
14         small [i] = (ll) small[i - 1] * A % P ;
15     }
16     big[0] = 1 % P ;
17     for (int i = 1 ; i < (1 << 15 ) ; i++) {
18         big[i] = (ll) big[i - 1] * small [1 << 15] % P ;
19     }
20     while (n --) {
21         ret += (ll) small [K & (1 << 15) - 1] * big [K >> 15] % P ;
22         if (ret >= P) ret -= P ;
23         K = ((ll) a * K + b) % m ;
24     }
25     printf ("Case #%d: %d\n" , ++ans , ret ) ;
26 }
27 
28 int main ()
29 {
30     //freopen ("a.txt" , "r" , stdin );
31     scanf ("%d" , &T) ;
32     ans = 0 ;
33     while (T--) {
34         scanf ("%d%d%d%d%d%d%d" , &n , &A , &K , &a , &b , &m , &P) ;
35         solve () ;
36     }
37     return 0 ;
38 }
View Code

 

在求A^X 幂时,快速幂求的话,是O(10^6*log(n)*40) = O(10^9) 肯定会超时,

我们将X转化成 x = i*s + j。

举例来说:

100200= 100000 + 200 ; 如果我们要求A^100200 可以 转换成求 (A^100000 ) * (A^200).

所以我们只需要将   小的数 && 大的数   分别打表存在small[] , big[]中即可。

铭神给的代码里是用二进制表示的。题目里的数据是1 ~ 10^9。所以最大不会超过1 << 30 (10亿7千多万)

所以任何一个f(x) = j         +        ((1 << 15 ) * i )       来表示

big[]     :       A^1 ,     A^2 ,     A^ 3  ,     A^ 4 …… A^s  (用s表示 1 << 15)

small[]  : A^(s * 1) , A^(s * 2) ,A^( s * 3)  ,A^( s * 4) …… A^(s * s)

这样O(1)复杂度内就能找到 A^f(x)

这样每次求A^x,便可以通过这两个数组在O(1)的时间复杂度内求出来,这样时间复杂度就变成了O(10^6*40) = O(4*10^7)了

 附代码:

转载于:https://www.cnblogs.com/get-an-AC-everyday/p/4399259.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值