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

本文详细解析了 Codeforces D.SameGCDs 的解题思路,通过提取最大公约数并利用欧拉函数计算与给定数互素的数的数量,提供了一种高效解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D. Same GCDs, Educational Codeforces Round 81 (Rated for Div. 2)

http://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.

思路
首先提取a,m的最大公约数g,令 a = x g , m = y g a = xg,m = yg 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) gcd(xg,yg)=gcd(xg+z,yg)

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

那么满足所有 g c d ( x + k , y ) = 1 gcd(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) gcd(x,y)=gcd(y,x%y),故当 x + k ∈ ( y , x + y ) x+k \in (y,x+y) x+k(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) gcd(x+k,y)=gcd(y,x+ky),而 x + k − y ∈ ( 0 , x ) x+k-y \in (0,x) x+ky(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值