Same GCDs
You are given two integers a nd m.Calculate the number of integers x such that0≤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≤10^10).
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
Output
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 + x)≥m,则gcd(a + x,m)= gcd(a + x-m,m)。
所以我们可以声明
我们正在看m个不同的整数x’=(a + x)modmx’=(a + x)modm,其中0≤x’<m,所以所有x’都形成一个段[0,m-1]。
因此,我们需要找到’x’(0≤x’<m)的数量,使得gcd(x’,m)= gcd(a,m)。
让我们表示g = gcd(a,m),然后a = ga’和m = gm’。
因此,gcd(a,m)= gcd(ga’,gm’)=g⋅gcd(a’,m’)= g或gcd(a’,m’)= 1。
由于gcd(x’,m)= gcd(a,m)= g所以我们也可以
代表x’= x“ g,因此gcd(x”,m’)= 1。
由于0≤x’<m,则0≤x“ <m’,或者我们需要计算x”的数量(0≤x“ <m’),以便gcd(x”,m’)= 1。
因为gcd(0,m’)= m’> 1,所以我们可以考虑x“∈[1,m’−1],这是欧拉totient的定义
函数φ(m’)就是答案。
可以使用m’= ∏i = 1lpaii的因式分解来计算Euler的上位函数φ(m’)。
则φ(m’)= m’∏i = 1(1-1pi)。
我的思路:
求满足gcd(a+x,m)=gcd(a,m)的x的个数
已知:
(令g=)gcd((a+x)%m,m)=gcd(a,m)
令x’=(a+x)%m, x’=x”*g
(因为m=m’*g, 所以gcd(x”,m’)=(1/g)
gcd(g*x”,g*m’)=(1/g)
gcd(x’,m))=1
那么, 求x的个数(因为a<=a+x<a+m,即x_max-x_min<m)èx’=(a+x)%m的个数=x的个数(又因为x’=x”*g线性关系)è 求x”的个数(x’=(a+x)%m -> 0<=x’<m -> 0<=x”<m’)
即求0<=x”<m’时gcd(x”,m’)=1的个数
就等于(1-1/m’的因子)的乘积(?)
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a,long long b) {
if(a%b==0) return b;
else return gcd(b,a%b);
}
int main() {
intT;
long long a,m;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&a,&m);
long long x2,m1,g;
g=__gcd(a,m);
m1=m/g;
long long ans=m1;
for(int i=2;i<=sqrt(m1);i++)
{
if(m1%i==0)
{
ans=ans/i*(i-1);
while(m1%i==0)m1/=i;
}
}
if(m1>1)ans=ans/m1*(m1-1);
printf("%lld\n",ans);
}
}