Codeforces 919E - Congruence Equation【数论-欧拉降幂】

E. Congruence Equation

time limit per test 3 seconds memory limit per test 256 megabytes

Problem Description

After trying hard for many years, Little Q has finally received an astronaut license. To celebrate the fact, he intends to buy himself a spaceship and make an interstellar travel.

Given an integer x. Your task is to find out how many positive integers n (1 ≤ n ≤ x) satisfy na n ∗ a n n b(mod b ( m o d p p )

where a, b, p are all known constants.

Input

The only line contains four integers a, b, p, x (2 ≤ p ≤ 106 + 3, 1 ≤ a, b < p, 1 ≤ 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.

【题意】

求出【1,x】中满足na n n b(mod b ( m o d p p )的n的个数。

【思路】

很容易知道 n n mod p的循环节为 p p

再根据费马小定理:若c为质数, a a p1 1 1 (mod p),可以得到 a a n的循环节为 p1 p − 1

那么我们可以得到 na n ∗ a n n 的循环节即为P= p(p1) p ∗ ( p − 1 )

因为 a a n的循环节为 p1 p − 1 ,我们可以令 n=i(p1)+j n = i ∗ ( p − 1 ) + j

然后我们根据欧拉降幂公式:若c为质数, a a b mod c c a a b%(c 1) (mod c c )

那么na n n na n ∗ a n n %(p- 1 1 ) b b (mod p)

所以 na n ∗ a j j b b (mod p)

i(p1)+j i ∗ ( p − 1 ) + j ba b ∗ a j − j (mod p p )

i=jba j − j

于是我们就可以通过在【0 p2 p − 2 】范围内枚举 j j ,然后通过上面的②再算出i代入①得到一个n,然后再判断+ P P 、+2P…..后是否在x范围内即可统计个数。

#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define rush() int T;scanf("%d",&T);while(T--)

typedef long long ll;
const int maxn = 200005;
const ll mod = 1e9+7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-9;

ll a,b,p,x;

ll fast_mod(ll a,ll n,ll Mod)
{
    ll ans=1;
    a%=Mod;
    while(n)
    {
        if(n&1) ans=(ans*a)%Mod;
        a=(a*a)%Mod;
        n>>=1;
    }
    return ans;
}

int main()
{
    scanf("%lld%lld%lld%lld",&a,&b,&p,&x);
    ll ans=0;
    ll Mod=p*(p-1);
    for(ll j=0;j<p-1;j++)
    {
        ll inv=fast_mod(fast_mod(a,j,p),p-2,p);  //a^j的逆元
        ll tmp=inv*b%p;
        ll i=(j-tmp+p)%p;
        ll n=(i*(p-1)+j)%Mod;
        if(n==0) n=Mod;
        ans+=x/Mod+(x%Mod>=n);
    }
    printf("%lld\n",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值