您的位置:首页 > 其它

Hdu2588 GCD 欧拉函数

2016-07-13 11:14 302 查看
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

Outpu

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且与n互质的所有数的个数,但是无法求出最大公约数是否大于m

但是可以这样想:

设a为大于等于m的n的一个约数,那么euler(n/a)表示的就是所有小于n/a与n/a互质的数的个数;

设其中任意一个数为x,那么这些数再乘以a就有gcd(n,x*a)=a;

可以想到答案为所有n大于等于m的约数ai的euler(n/ai)之和.

下证明这些数不会重复:

设a、b为两个不同的大于等于m的n的约数,假设存在重复,

那么就有a*x=b*y (x是小于等于n/a且与n/a互质的数,y是n/b的。。)

变形,得到x*n/b=y*n/a;

由于x和n/a互质,所以x是y的约数;

同理y是x的约数,这显然推出x=y,即a=b矛盾!

最后注意一下,m=1的时候答案就是n;

还有n如果是平方数的话,需要删去多余部分。

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
#define LL long long
int Euler(int n){
int res=n,i,m;
m=sqrt(n+0.5);
for(i=2;i<=m;i++){
if(n%i==0){
n/=i;
res=res-res/i;
while(n%i==0)
n/=i;
}
}
if(n>1){
res=res-res/n;
}
return res;
}

void f(int n,int m)
{
int i,j,s=0,x;
x=sqrt(n+0.5);
if(m==1) printf("%d\n",n);
else{
for(i=2;i<=x;++i){
if(n%i==0){
if(i>=m) s+=Euler(n/i);
if(n/i>=m) s+=Euler(i);
}
}
if(x*x==n&&x>=m) s-=Euler(x);
printf("%d\n",s+1);
}
}
int main()
{
int t,n,m;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
f(n,m);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: