-
由于a,m都是给定的,所以记d=gcd(a,m) .
-
由辗转相除法得 gcd(a+x,m)=gcd((a+x)%m , m)
-
由于0<=x<m,a>=1所以(a+x)%m的范围是[0,m-1]
-
记t=(a+x)%m,0<=t<=m-1,我们要求的东西就是满足
gcd(t,m)==d,0<=t<m
的t的个数。 我们令t=ad,m=bd,那么就等价于求满足gcd(a,b)==1,0<=a<b)
的a的个数,这个值就等于b的欧拉函数值。
P h i ( x ) = x ∗ ∏ 1 q ( p ( i ) − 1 ) / p ( i ) Phi(x)=x* \prod_{1}^{q} (p(i)-1)/p(i) Phi(x)=x∗∏1q(p(i)−1)/p(i)
p(i)是x的第i个素因子。
#include<bits/stdc++.h>
using namespace std;
//#pragma GCC optimize(2)
#define ull unsigned long long
#define ll long long
#define pii pair<int, int>
const int maxn = 1e6 + 10;
const ll mod = 1e9 + 7;
const ll inf = (ll)4e16+5;
const int INF = 1e9 + 7;
const double pi = acos(-1.0);
ll inv(ll b){
while(b==1)return 1;return(mod-mod/b)*inv(mod%b)%mod;}
inline ll read()
{
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){
while(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){
x=x*10+ch-'0';ch=getchar();}
return x*f;
}
ll a,m;
void solve(ll x)
{
ll ans=x;
for(ll i=2;i*i<=x;i++)
{
if(x%i==0)
{
ll t=i;
ans=ans/t*(t-1);//先除再乘 不然爆ll
while(x % t == 0)
{
x/=t;
}
}
}
if(x > 1) ans=ans/x*(x-1); //别漏了这里 最终还剩下一个非合数 特判是不是素数
cout<<ans<<'\n';
}
int main()
{
int t;cin>>t;
while(t--)
{
cin>>a>>m;
ll d=__gcd(a,m);
//phi(m/d)
solve(m/d);
}
return 0;
}