HDU2588(欧拉函数的应用)

打开百度搜索了莫比乌斯,来自哔哩哔哩的一个视频讲的非常的好:

https://www.bilibili.com/video/av14325327/

不过他在讲莫比乌斯反演之前,先讲了两道欧拉函数应用的题:

HDU2588 和bzoj2818

GCD

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3858    Accepted Submission(s): 2087


 

Problem Description

The greatest common divisor GCD(a,b) of two positive integers a and b,sometimes written (a,b),is the largest divisor common to a and b,For example,(1,2)=1,(12,18)=6.
(a,b) can be easily found by the Euclidean algorithm. Now Carp is considering a little more difficult problem:
Given integers N and M, how many integer X satisfies 1<=X<=N and (X,N)>=M.

Input

The first line of input is an integer T(T<=100) representing the number of test cases. The following T lines each contains two numbers N and M (2<=N<=1000000000, 1<=M<=N), representing a test case.

 

Output

For each test case,output the answer on a single line.

 

Sample Input

3

1 1

10 2

10000 72

 

Sample Output

1

6

260

 

题意:给出N和M,问gcd(x,n)>=M的合法对数。

我理解的做法大概是

第一步:令一个p=gcd(x,n),由于gcd的性质可知  存在某个a,b使得p*a=x,p*b=n

第二步:得到的a,b还有后面两个性质   gcd(a,b)=1,a<=b  (若统计a的个数 很像欧拉函数)

可以转换为求gcd(a,b)=1合法的对数

第三步:通过从1到n枚举p,(条件n%p==0)得到b,再由b找合法a的个数(欧拉函数)

综上  代码:

#include
using namespace std;
typedef long long ll;
ll phi(ll n){
	ll ans = n;
	for(ll i=2; i<=sqrt(n); i++){
		if(n%i==0){
			ans = ans/i*(i-1);
			while(n%i==0)n/=i;
		}
	}
	if(n>1)ans = ans/n*(n-1);
	return ans;
}
int main()
{
	int t;
	cin>>t;
	ll n,m;
	while(t--)
	{
		scanf("%lld%lld",&n,&m);
		ll ans=0;
		for(ll i=1;i*i<=n;i++)
		{
			if(n%i==0) 
			{
				if(i>=m) ans+=phi(n/i);
				if(i*i!=n&&n/i>=m) ans+=phi(i);
			}
		}
		printf("%lld\n",ans);
	}
}

 

你可能感兴趣的:(HDU2588(欧拉函数的应用))