D. Same GCDs, Educational Codeforces Round 81 (Rated for Div. 2),欧拉函数

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,令 a = x g , m = y g a = xg,m = yg

需要使得 g c d ( x g , y g ) = g c d ( x g + z , y g ) gcd(xg,yg) = gcd(xg+z,yg)

易知z为g的倍数,令 z = k g , k [ 0 , y ) z = kg,k \in [0,y)

那么满足所有 g c d ( x + k , y ) = 1 gcd(x+k,y) = 1 的k都可以,即求[x,y+x)中与y互素的数的个数

因为a < m,那么可知x < y,则要分别算[x,y],(y,x+y)中与y互素的数的个数

因为 g c d ( x , y ) = g c d ( y , x % y ) gcd(x,y) = gcd(y,x\%y) ,故当 x + k ( y , x + y ) x+k \in (y,x+y) 时, g c d ( x + k , y ) = g c d ( y , x + k y ) gcd(x+k,y) = gcd(y,x+k-y) ,而 x + k y ( 0 , x ) x+k-y \in (0,x)

所以(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;
}
发布了50 篇原创文章 · 获赞 3 · 访问量 3095

猜你喜欢

转载自blog.csdn.net/xing_mo/article/details/104111794