题解:CF919E Congruence Equation

· · 题解

给定 x,a,b,p,问有多少个 n,满足 1\le n \le x,且:

n \cdot a^n \equiv b \pmod p

其中 1 \le p \le 10^6 + 3,1 \le a,b < p,1\le x\le 10^{12},p 为质数。

思路

看到 a^n 和 p(p 为质数),我们由费马小定理知道 a^n \bmod p 仅 a^0,a^1 \cdots a^{p-2} 带来的 p-1 种取值。

于是我们令 n \equiv i \pmod {p-1},得到 a^n \equiv a^i \pmod p。

带入原方程得 n \cdot a^i \equiv b \pmod p \to n \equiv {(a^i)} ^ {-1} \cdot b \pmod p。

于是我们得出关于 n 的同余方程组:

\begin{cases} n \equiv {(a^i)} ^ {-1} \cdot b &\pmod p\\ n \equiv i &\pmod {p-1} \end{cases}

因为一定满足 p \perp (p-1),这个就可以用 CRT 求出最小解 n_i^*,那么通解为 n_i^* + kp(p-1)\le x,k\in N,所以 k \le \bigg\lfloor\dfrac{x - n_i^*}{p(p-1)}\bigg\rfloor。

统计每个 i 对应多少 k,求和。

/*
_/        _/   _/_/_/_/_/_/   _/        _/         _/_/
_/        _/        _/        _/_/      _/       _/   _/
_/        _/        _/        _/  _/    _/      _/     _/
_/_/_/_/_/_/        _/        _/    _/  _/     _/       _/
_/        _/        _/        _/      _/_/     _/_/_/_/_/_/
_/        _/        _/        _/        _/    _/          _/
_/        _/   _/_/_/_/_/_/   _/        _/   _/            _/
*/
#include<iostream>
#include<cstdio>
#include<climits>
#define re register
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
    template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
    template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
    template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
    template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;
ll a,b,p,x ;
ll n,r[3],inv,y,mul = 1,cnt ;
ll M = 1,m[3],k[3],t[3] ;
inline void exgcd (ll a,ll &x,ll b,ll &y) {
    if (!b) {
        x = 1,y = 0 ;
        return ;
    }
    exgcd(b,y,a % b,x) ;
    y -= a / b * x ;
}
int main () {
    read(a,b,p,x) ;
    m[1] = p,m[2] = p - 1 ;
    for (re int i = 1 ; i <= 2 ; ++i) M *= m[i] ;
    for (re int i = 1 ; i <= 2 ; ++i) {
        k[i] = M / m[i] ;
        exgcd(k[i],t[i],m[i],y) ;
        ((k[i] %= M) += M) %= M ;
        ((t[i] %= M) += M) %= M ;
    }
    for (re int i = 0 ; i < p - 1 ; ++i) {
        exgcd(mul,inv,p,y) ;
        ((inv %= p) += p) %= p ;
        r[1] = b * inv % p,r[2] = i ;
        for (re int j = 1 ; j <= 2 ; ++j) (n += (__int128)k[j] % M * t[j] % M * r[j] % M) %= M ;
        if (n <= x) cnt += (x - n) / M + 1 ;
        mul = mul * a % p,n = 0 ;
    }
    write(cnt) ;
    return 0 ;
}