hdu 2588 GCD(欧拉函数)

来源:互联网 发布:淘宝上怎么删除评价 编辑:程序博客网 时间:2024/06/05 05:20

GCD

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

借鉴大神原话:
 ①首先,补充一下关于GCD()的一些基础知识。
  1,如果GCD(a,b)=c,则可以知道GCD(a/c,b/c)=1;( GCD(a,b)=c <=> GCD(a/c,b/c)=1 )
  2,设GCD(a,b)=c,如果想要GCD(a,b*d)=c,用①_1可知,
    只需满足GCD(a/c,(b/c)*d)=1即可(这个限制既为,满足最大公约数的要求).

 ②然后,我们所要求的是GCD(X,N)>=M,也就是说我们要求一个GCD(X,N)=Z,的数,
  1,如果M==1,则可以知道在[1,N]中任意数X的GCD(X,N)>=1,所以符合要求的个数为N。
  2,如果M>1,则表示我们需要找一个GCD(X,N)>1的数。这样我们就知道X肯定会是N的除了1以外的约数、
  因为,X只有是N除了1以外的约数,才可能会有GCD(X,N)>1存在。而且,GCD(N,X)=X;(约数嘛,你懂得~)

 ③再者,我们需要统计的数符合要求的X的个数呢?
  1,正如②_2可以知道GCD(N,X)=X,能够使得GCD()=X的数不一定只有X本身,说的正确点的应该是GCD(N,X*q)=X,
  只需要计算1~N中有多少个(X*q)即可。但是,q是有受限制的,需要满足上述①_2的要求。
         (比如:GCD(15,5)=5,GCD(15,5*3)=15;)
  2,由①_2可知,要使得GCD(N,X*q)=X,需要满足GCD(N/X,q)=1.也就是统计1~N/X中有多少个数与N/X互质。
是不是觉得有点熟悉了的?=>求1~N中,有多少个与N互质的数,不就是欧拉函数嘛,SUM+=Eular(N/X);
 ④最后,如何不重复的统计其公约数为符合条件X的数呢?
  其实,你每次用欧拉函数统计出来的那些数,都是唯一的,如上面③_2所说的,q是有受限制的,因为这个限制,使得所求出的个数都为不重复的、所以,只需要统计N的符合要求的约数Xi,SUM+=Eular(N/Xi),既为答案。

代码:

#include<stdio.h>int Euler(int n){    int res=n;    for(int i=2;i*i<=n;++i)    {        if(n%i==0)        {            res=res/i*(i-1);            while(n%i==0)                n/=i;        }    }    if(n>1)        res-=res/n;    return res;}int main(){    int t,n,m;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        int ans=0;        for(int i=1;i*i<=n;++i)        {            if(n%i==0)            {                if(i>=m)                    ans+=Euler(n/i);                if(i*i!=n&&n/i>=m)                    ans+=Euler(i);            }        }        printf("%d\n",ans);    }    return 0;}