跳到正文

题解

题解:CF919E Congruence Equation

_Sorasaki_Hina_约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年6月24日
更新
2026年6月24日
篇幅
约 5 分钟
获赞
1
题目
CF919E

版本

  1. v1当前

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

n⋅an≡b(modp)n \cdot a^n \equiv b \pmod p

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

思路

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

于是我们令 n≡i(modp−1)n \equiv i \pmod {p-1},得到 an≡ai(modp)a^n \equiv a^i \pmod p。

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

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

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

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

统计每个 ii 对应多少 kk,求和。

C++
/*
_/        _/   _/_/_/_/_/_/   _/        _/         _/_/
_/        _/        _/        _/_/      _/       _/   _/
_/        _/        _/        _/  _/    _/      _/     _/
_/_/_/_/_/_/        _/        _/    _/  _/     _/       _/
_/        _/        _/        _/      _/_/     _/_/_/_/_/_/
_/        _/        _/        _/        _/    _/          _/
_/        _/   _/_/_/_/_/_/   _/        _/   _/            _/
*/
#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 ;
}
原文