2023牛客暑期多校训练营9-B Semi-Puzzle: Brain Storm
https://ac.nowcoder.com/acm/contest/57363/B
文章目录
- 2023牛客暑期多校训练营9-B Semi-Puzzle: Brain Storm
- 题意
- 解题思路
- 代码
题意
解题思路
欧拉定理
a
b
≡
{
a
b
%
φ
(
p
)
g
c
d
(
a
,
p
)
=
1
a
b
g
c
d
(
a
,
p
)
≠
1
,
b
<
φ
(
p
)
a
b
%
φ
(
p
)
+
φ
(
p
)
g
c
d
(
a
,
p
)
≠
1
,
b
≥
φ
(
p
)
a^b\equiv \begin{cases} &a^{b\%\varphi(p)}~~&gcd(a,p)=1\\ &a^b~~&gcd(a,p)\neq 1,b<\varphi(p)\\ &a^{b\%\varphi(p)+\varphi(p)}~~&gcd(a,p)\neq 1,b\ge\varphi(p) \end{cases}
ab≡⎩
⎨
⎧ab%φ(p) ab ab%φ(p)+φ(p) gcd(a,p)=1gcd(a,p)=1,b<φ(p)gcd(a,p)=1,b≥φ(p)
a
u
≡
u
(
m
o
d
p
)
设
d
=
u
%
φ
(
p
)
+
φ
(
p
)
u
=
d
+
k
φ
(
p
)
a
d
+
k
φ
(
p
)
≡
d
+
k
φ
(
p
)
(
m
o
d
p
)
a
d
−
d
≡
k
φ
(
p
)
(
m
o
d
p
)
\begin{matrix} a^u\equiv u\pmod p\\ 设d=u\%\varphi(p)+\varphi(p)\\ u=d+k\varphi(p)\\ a^{d+k\varphi(p)}\equiv d+k\varphi(p)\pmod p\\ a^d-d\equiv k\varphi(p)\pmod p \end{matrix}
au≡u(modp)设d=u%φ(p)+φ(p)u=d+kφ(p)ad+kφ(p)≡d+kφ(p)(modp)ad−d≡kφ(p)(modp)
将取余打开,可得:
φ
(
p
)
x
+
p
y
=
a
d
−
d
\begin{matrix} \varphi(p)x+py=a^d-d \end{matrix}
φ(p)x+py=ad−d
显然可以用扩展欧几里得求解当
φ
(
p
)
x
+
p
y
=
gcd
(
p
,
ϕ
(
p
)
)
\varphi(p)x+py=\gcd(p,\phi(p))
φ(p)x+py=gcd(p,ϕ(p))的解,为保证
d
d
d有解,故
gcd
(
p
,
φ
(
p
)
)
∣
a
d
−
d
\gcd(p,\varphi(p))\mid a^d-d
gcd(p,φ(p))∣ad−d,设
a
d
−
d
=
h
gcd
(
φ
(
p
)
,
p
)
a^d-d=h\gcd(\varphi(p),p)
ad−d=hgcd(φ(p),p),故
a
d
=
h
gcd
(
φ
(
p
)
,
p
)
+
d
a^d=h\gcd(\varphi(p),p)+d
ad=hgcd(φ(p),p)+d,可以发现
a
d
≡
d
(
m
o
d
gcd
(
φ
(
p
)
,
p
)
)
a^d\equiv d\pmod{\gcd(\varphi(p),p)}
ad≡d(modgcd(φ(p),p)),可以发现形式上与
a
u
≡
u
(
m
o
d
p
)
a^u\equiv u\pmod p
au≡u(modp),显然当
p
=
1
p=1
p=1时,
u
=
0
u=0
u=0,有了边界条件,可以递归求出
u
u
u。
u
=
d
+
k
φ
(
p
)
u=d+k\varphi(p)
u=d+kφ(p),
k
k
k即为
φ
(
p
)
x
+
p
y
=
a
d
−
d
\varphi(p)x+py=a^d-d
φ(p)x+py=ad−d中
x
x
x的解,当求出
φ
(
p
)
x
0
+
p
y
0
=
gcd
(
p
,
ϕ
(
p
)
)
\varphi(p)x_0+py_0=\gcd(p,\phi(p))
φ(p)x0+py0=gcd(p,ϕ(p)):
x
=
x
0
×
(
a
d
−
d
gcd
(
φ
(
p
)
,
p
)
%
p
)
=
x
0
×
(
(
a
d
−
d
)
%
p
gcd
(
φ
(
p
)
,
p
)
)
\begin{matrix} x=&x_0\times(\dfrac{a^d-d}{\gcd(\varphi(p),p)}\% p)\\ =&x_0\times(\dfrac{(a^d-d)\% p}{\gcd(\varphi(p),p)}) \end{matrix}
x==x0×(gcd(φ(p),p)ad−d%p)x0×(gcd(φ(p),p)(ad−d)%p)
代码
#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
using namespace std;
ll T,a,m;
ll phi(ll n){
ll sum=n;
for(ll i=2;i*i<=n;i++){
if(n%i==0){
while(n%i==0)n/=i;
sum/=i,sum*=i-1;
}
}
if(n>1)return sum/n*(n-1);
return sum;
}
ll exgcd(ll a,ll b,ll &x,ll &y){
if(!b){
x=1,y=0;
return a;
}
ll v=exgcd(b,a%b,y,x);
y-=a/b*x;
return v;
}
ll power(ll x,ll p,ll mod){
ll res=1;
while(p){
if(p&1)res*=x,res%=mod;
x*=x,x%=mod;
p>>=1;
}
return res;
}
ll dfs(ll a,ll p){
if(p==1)return 0;
ll ph=phi(p);
ll x,y;
ll v=exgcd(ph,p,x,y);
x=(x%p+p)%p;
ll d=dfs(a,v)+ph;
return d+(x*((power(a%p,d,p)-d%p+p)%p/v)%p)*ph;
}
void solve(){
cin>>a>>m;
ll x=dfs(a,m);
cout<<x<<'\n';
}
int main(){
cin>>T;
while(T--)solve();
}