codeforces919e(逆元 同余方程)

E. Congruence Equation
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Given an integer x. Your task is to find out how many positive integers n (1 ≤ n ≤ x) satisfy

where  a, b, p are all known constants.
Input

The only line contains four integers a, b, p, x (2 ≤ p ≤ 106 + 31 ≤ a, b < p1 ≤ x ≤ 1012). It is guaranteed that p is a prime.

Output

Print a single integer: the number of possible answers n.

Examples
input
2 3 5 8
output
2
input
4 6 7 13
output
1
input
233 233 10007 1
output
1
Note

In the first sample, we can see that n = 2 and n = 8 are possible answers.


题意:求小于等于x的满足上面同余方程的n个数。


数论白痴上线。

参考了http://blog.csdn.net/baidu_36797646/article/details/79225155的博文。

思路:n%p的周期为p,a^n%p的周期为p-1,则(n*(a^n))%p的周期为p*(p-1),只要算一个周期里面满足的就好。但是这个周期太大,想到利用n%p和a^n%p的周期差,n每增加p-1,n%p减1,a^n%p不变,这样就可以对于枚举1~p-1的n,设m=n+k*(p-1),(1<=m<=P)一个周期内必有一个m满足同余方程。

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
typedef long long ll;
ll MOD;
ll a,b,p,x;
ll quick_pow(ll a,ll b)
{
	ll ans=1;
	while(b)
	{
		if(b&1)ans=(ans*a)%MOD;
		b>>=1;
		a=(a*a)%MOD;
	}
	return ans;
}
int main()
{
	while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&p,&x))
	{
		ll P=(p-1)*p;
		MOD=p;
		ll k;
		ll ans=0;
		for(ll n=1;n<p;n++)
		{
			if(n>x)break;
			k=(b*(quick_pow(quick_pow(a,n),p-2)))%MOD;
			ll c;
			if(n>=k)
				c=(n+(n-k)*(p-1))%P;
			else
				c=(n+(n+p-k)*(p-1))%P;
			if(c==0)c=P;
			ans+=(x/P)+(x%P>=c?1:0);
		}
		printf("%I64d\n",ans);
	}
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值