hdu 2588 GCD(欧拉函数)

题目链接:http://hdu.hustoj.com/showproblem.php?pid=2588

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,求有多少x满足gcd(x,n)>=m。


题目思路:

假设一个gcd(x,n)=s

那么s*a = x;

      s*b = n;

则a<=b(因为x<=n)且gcd(a,b)=1;

发现什么没有,这就是欧拉函数,求出小于等于b且与b互质的a的个数就是x的数量。

所以我们就可以枚举s,要求s>=m。因为n比较大,所以枚举到sqrt(n),另一个直接算。


欧拉函数代码可看:


代码:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<map>

using namespace std;

#define FOU(i,x,y) for(int i=x;i<=y;i++)
#define FOD(i,x,y) for(int i=x;i>=y;i--)
#define MEM(aA,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)

const double EXP = 1e-9;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const ll MINF = 0x3f3f3f3f3f3f3f3f;
const double DINF = 0xffffffffffff;
const int mod = 1e9+7;

int phi(int x){
    int ans=x;
    for(int i=2;i*i<=x;i++){
        if(x%i == 0){
            ans = ans/i * (i-1);
            while(x % i==0) x/=i;
        }
    }
    if(x>1) ans = ans/x*(x-1);
    return ans;
}
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    std::ios::sync_with_stdio(false);
    int t,n,m;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        ll ans=0;
        for(int i=1;i*i<=n;i++)
        {
            if(n%i==0)
            {
                if(i>=m)
                    ans+=phi(n/i);
                if(i*i!=n)
                {
                    if(n/i>=m)
                        ans+=phi(i);
                }
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/baodream/article/details/80540857