GCD
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(2<=N<=1000000000, 1<=M<=N), 求1<=X<=N 且gcd(X,N)>=M的个数。
思路:数据量太大,用常规方法做是行不通的。所以这道题用到了欧拉函数。
欧拉函数
<mark>在数论,对正整数n,欧拉函数是小于n的正整数中与n互质的数的数目(φ(1)=1)</mark>。此函数以其首名研究者欧拉命名(Euler’s totient function),它又称为Euler’s totient function、φ函数、欧拉商数等。 例如φ(8)=4,因为1,3,5,7均和8互质。
欧拉函数知识点总结及代码模板
https://www.cnblogs.com/PJQOOO/p/3875545.html
这个博客里写的代码实现挺好懂的(看了好多其他的博客都没看懂代码为什么这么写)
至于这道题为什么用到欧拉函数:
<mark>设gcd(n,x)=d
则 n=p ∗d , x=q ∗d 且 p与q是互质的</mark>
因为n>=x所以要求d>=m时p的欧拉函数值。
#include<cstdio>
using namespace std;
int Euler(int n){
int m=n;
for(int i=2;i*i<=n;i++){
if(n%i==0)//第一次找到的必为素因子
{
m-=m/i;//把是素因子i的倍数的数的数目减掉 i,2i,3i,···,(m/i)*i
while(n%i==0)
n/=i;//把该素因子全部约掉
}
}
if(n>1) //还有一个比根号n大的素因子 ,也就是现在这个n
m-=m/n;
return m;
}
int main(){
int T;
scanf("%d",&T);
int N,M;
while(T--){
scanf("%d%d",&N,&M);
long long sum=0;
for(int i=1;i*i<=N;i++){//只遍历到根号n,节省时间
if(N%i==0){
if(i>=M) sum+=Euler(N/i);//i为N的约数(1<=i<=根号n)
if((N/i)!=i&&(N/i)>=M) sum+=Euler(i);//(N/i)是N的约数,(N/i)>=根号N
}
}
printf("%lld\n",sum);
}
return 0;
}