题意:
给定 a , m a,m a,m,求满足 g c d ( a , m ) = g c d ( a + x , m ) gcd(a,m)=gcd(a+x,m) gcd(a,m)=gcd(a+x,m)的 x x x的个数,且 0 < = x < m 0<=x<m 0<=x<m。
思路:
由辗转相除法得:
g
c
d
(
a
+
x
,
m
)
=
g
c
d
(
(
a
+
x
)
m
o
d
m
,
m
)
gcd(a+x,m)=gcd((a+x)\bmod m,m)
gcd(a+x,m)=gcd((a+x)modm,m)
而
(
a
+
x
)
m
o
d
m
(a+x)\bmod m
(a+x)modm正好是在
[
0
,
m
−
1
]
[0,m-1]
[0,m−1]的数,与
x
x
x范围吻合。考虑继续化简。
令
g
c
d
(
a
,
m
)
=
d
gcd(a,m)=d
gcd(a,m)=d,那么
g
c
d
(
(
a
+
x
)
d
,
m
d
)
=
g
c
d
(
(
a
+
x
)
m
o
d
m
d
,
m
d
)
=
1
gcd(\frac{(a+x)}{d},\frac{m}{d})=gcd(\frac{(a+x)\bmod m}{d},\frac{m}{d})=1
gcd(d(a+x),dm)=gcd(d(a+x)modm,dm)=1
可知
(
a
+
x
)
m
o
d
m
d
\frac{(a+x)\bmod m}{d}
d(a+x)modm与
m
d
\frac{m}{d}
dm互质。由于
(
a
+
x
)
m
o
d
m
<
m
(a+x)\bmod m<m
(a+x)modm<m,对应
x
x
x取值
[
0
,
m
−
1
]
[0,m-1]
[0,m−1],答案即为与
m
d
\frac{m}{d}
dm互质的数,即
m
d
\frac{m}{d}
dm的欧拉函数。
当然也可以用莫比乌斯做,但是大材小用了。
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;
//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;
LL a,m;
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
int _; scanf("%d",&_);
while(_--)
{
scanf("%lld%lld",&a,&m);
LL ans=m/__gcd(a,m);
m/=__gcd(a,m);
for(LL i=2;i<=m/i;i++)
if(m%i==0)
{
while(m%i==0) m/=i;
ans=ans/i*(i-1);
}
if(m>1) ans=ans/m*(m-1);
printf("%lld\n",ans);
}
return 0;
}
/*
*/