【简单数论】H - A^X mod P_HRBUST - 2049_31行代码AC

立志用最少的代码做最高效的表达


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 ) ) m o d u l a r P . ( A^{f(1)} + A^{f(2)} + A^{f(3)}+ ...... + A^{f(n)} ) modular P. (Af(1)+Af(2)+Af(3)+......+Af(n))modularP.

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


分析

1e9的规模,即使O(n)的复杂度也没办法通过,因此考虑将指数分解

把指数 f(x) 分解为 f ( x ) = a k + b f(x) = ak+b f(x)=ak+b,这样一来, A f ( x ) = A a k ∗ A b A^{f(x)} = A^{ak} * A^b Af(x)=AakAb

上式中的 k 和要打的表的大小有关,哪表开多大合适呢?理论上开 33333 就可以了,因为 sqrt(1e9) = 33333。这样只要计算 ( A 1 ) % P 、 ( A 2 ) % P … … ( A 33333 ) % P (A^1)\%P 、(A^2)\%P …… (A^{33333})\%P (A1)%P(A2)%P(A33333)%P 以及 ( A 1 ∗ 33333 ) % P ( A 2 ∗ 33333 ) % P … … ( A 33333 ∗ 33333 ) % P (A^{1*33333})\%P (A^{2*33333})\%P ……(A^{33333*33333})\%P (A133333)%P(A233333)%P(A3333333333)%P ,对于 A f ( x ) A^{f(x)} Af(x),我们就可以通过上面两个数组相乘的结果得到了。

注意:

由于代码中涉及到乘法运算,所以 int 型会溢出,可以全部开 long long。


#include<bits/stdc++.h>
#define len 35000
using namespace std;

typedef long long gg;
gg n, A, K, a, b, m, P;
gg dp1[len + 10], dp2[len + 10]; 

void init() {
	gg i;
	dp1[0] = dp2[0] = 1;
	for(i = 1; i <= len; i++) 
		dp1[i] = (dp1[i-1]*A)%P;
	dp2[1] = dp1[len];
	for(i = 2; i <= len; i++)
		dp2[i] = (dp2[i-1]*dp2[1])%P;
}

int main() {
	gg T; cin >> T; 
	for(gg j = 1; j <= T; j++){
		cin >> n >> A >> K >> a >> b >> m >> P;
		init();
		gg ans = 0;
		for(gg i = 1; i <= n; i++) {
			ans = (ans + (dp1[K%len]*dp2[K/len])%P)%P;
			K = (a * K + b) % m;
		}
		printf("Case #%lld: %lld\n", j, ans);
	}
	return 0;
} 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来老铁干了这碗代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值