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 n∗a 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】中满足 n n b(mod b ( m o d p p )的的个数。
【思路】
很容易知道 n n mod 的循环节为 p p
再根据费马小定理:若为质数, a a ≡ ≡ 1 1 (mod ),可以得到 a a 的循环节为 p−1 p − 1
那么我们可以得到 n∗a n ∗ a n n 的循环节即为= p∗(p−1) p ∗ ( p − 1 )
因为 a a 的循环节为 p−1 p − 1 ,我们可以令 n=i∗(p−1)+j n = i ∗ ( p − 1 ) + j ① ①
然后我们根据欧拉降幂公式:若为质数, a a mod c c a a b%c − − 1 (mod c c )
那么 n n n∗a n ∗ a n n %(- 1 1 ) b b (mod )
所以 n∗a n ∗ a j j b b (mod ) ③ ③
i∗(p−1)+j i ∗ ( p − 1 ) + j ≡ ≡ b∗a b ∗ a −j − j (mod p p )
−j − j ② ②
于是我们就可以通过在【, p−2 p − 2 】范围内枚举 j j ,然后通过上面的②再算出代入①得到一个n,然后再判断+ P P 、+…..后是否在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);
}