A^X mod P

E - A^X mod P

题目链接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2605


Time Limit:5000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

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
 
   
 
   

一种很不错的优化方式。

运用预处理的两个数组进行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就能表示成f2[x/(10^5)]*f1[x%(10^5)]。

从而用空间换取时间。

下面是代码:
#include <stdio.h>
typedef long long ll;
ll  dp1[150000];
ll dp2[150000];
int main()
{
	ll n,A,K,a,b,m,p;
	int t;
	int nn=0;
	scanf("%d",&t);
	while(t--)
	{
		++nn;
		scanf("%lld%lld%lld%lld%lld%lld%lld",&n,&A,&K,&a,&b,&m,&p);
		dp1[0]=dp2[0]=1;
		dp1[1]=A%p;
		for(int i=2;i<=100000;i++)
		{
			dp1[i]=(dp1[i-1]*dp1[1])%p;
		}
		dp2[1]=dp1[100000];
		for(int i=2;i<=100000;i++)
			dp2[i]=(dp2[i-1]*dp2[1])%p;
		long long ans=0,f=K;
		for(int i=0;i<n;i++)
		{
			ans=(ans+dp2[f/100000]*dp1[f%100000])%p;
			f=(a*f+b)%m;
			
		}
		printf("Case #%d: %lld\n",nn,ans);
		
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值