题目链接:https://codeforces.com/contest/1295/problem/D
You are given two integers a and m. Calculate the number of integers x such that 0≤x<m and gcd(a,m)=gcd(a+x,m).
Note: gcd(a,b) is the greatest common divisor of a and b.
Input
The first line contains the single integer T (1≤T≤50) — the number of test cases.
Next T lines contain test cases — one per line. Each line contains two integers a and m (1≤a<m≤1010).
Output
Print T integers — one per test case. For each test case print the number of appropriate x-s.
Example
input
3
4 9
5 10
42 9999999967
outpu
6
1
9999999966
Note
In the first test case appropriate x-s are [0,1,3,4,6,7].
In the second test case the only appropriate x is 0.
题意
给定数 a,m,求解 x 的个数。x 满足 x ∈ [0,m),gcd(a,m) = gcd(a+x,m)
思路
设a = xg,m = yg,则:
g
c
d
(
x
g
,
y
g
)
=
g
c
d
(
x
g
+
z
,
y
g
)
=
g
gcd(xg,yg) = gcd(xg+z,yg) = g
gcd(xg,yg)=gcd(xg+z,yg)=g
那么 z = kg,因为z∈[0,m),所以 k∈[0,y)
也就是 gcd(x+k,y) = 1
求解 k∈[x,x+y) 与 y 互质的数的个数
对于任意与 y 互质的数 p 和任意正整数 c
满足:
显然 p+cy 与 y 互质
那么分成两个区间来看:
对于[x,y]区间内,答案是 k∈[x,y] 与 y 互质的个数
对于(y,x+y)区间内,答案是 k∈(0,y) 与 y 互质的个数
两个答案区间合并,就是 φ(y)
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn = 100010;
ll gcd(ll a,ll b)
{
return b==0 ? a : gcd(b,a%b);
}
ll pri[maxn],tot;
bool v[maxn];
void primes()
{
tot = 0;
memset(v,true,sizeof(v));
for(ll i=2;i<maxn;i++){
if(v[i])
pri[++tot] = i;
for(ll j=1;j<=tot&&pri[j]*i<maxn;j++){
v[i*pri[j]] = false;
if(i%pri[j]==0) break;
}
}
}
ll phi(ll n)
{
ll ans = n;
for(ll i=1;pri[i]*pri[i] <=n;i++){
if(n%pri[i]==0){
ans = ans/pri[i]*(pri[i]-1);
while(n%pri[i]==0)
n /= pri[i];
}
}
if(n>1) ans = ans/n*(n-1);
return ans;
}
ll T,a,m,x,y;
int main()
{
cin>>T;
primes();
while(T--){
cin>>a>>m;
ll g = gcd(a,m);
x = a/g,y = m/g;
ll ans = phi(y);
cout<<ans<<endl;
}
}