D. Same GCDs, Educational Codeforces Round 81 (Rated for Div. 2)
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.
思路:
首先提取a,m的最大公约数g,令
需要使得
易知z为g的倍数,令
那么满足所有 的k都可以,即求[x,y+x)中与y互素的数的个数
因为a < m,那么可知x < y,则要分别算[x,y],(y,x+y)中与y互素的数的个数
因为 ,故当 时, ,而
所以(y,x+y)中与y互素的数的个数与(0,x)中与y互素的数的个数相等,故总的答案为[1,y]中与y互素的数的个数
#include<bits/stdc++.h>
#define ll long long
using namespace std;
long long gcd(long long a,long long b)
{
return b?gcd(b,a%b):a;
}
long long oula(long long n)
{
long long rea = n;
for(long long i = 2;i * i <= n;++i)
{
if(n % i == 0)
{
rea -= rea/i;
while(n % i == 0)
n /= i;
}
}
if(n > 1)
rea -= rea/n;
return rea;
}
int t;
ll a,b;
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld",&a,&b);
ll g = gcd(a,b);
a/=g,b/=g;
ll ans = oula(b);
printf("%lld\n",ans);
}
return 0;
}