1199. GCD

5 篇文章 0 订阅

Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

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 <= 3000) representing the number of test cases. The following T lines each contains two numbers N and M (1 <= N <= 1000000000, 0 <= M <= 1000000000), representing a test case. 

Output

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

Sample Input

31 110 210000 72

Sample Output

16260

Problem Source

ZSUACM Team Member


用到了欧拉函数。比x小并且和x互质的个数叫做他的欧拉函数。代码如下:

// Problem#: 1199
// Submission#: 2197105
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<iostream>
#include<cmath>
using namespace std;
/*

题意: 给定n和m, 求有多少x(m<=x<=n),满足 gcd(x,n)>=m.
可以利用欧拉函数来解答.  令 y = gcd ( x , n ),其中 y>=m ,则有 gcd(x/y,n/y)=1 .
于是对于特定的y,我们想求有多少 x 满足 gcd(x,n)=y, 只要求出有多少 x/y 小于 n/y 且与 n/y 互质——这正是欧拉函数的定义:φ(a) 表示小于a且和a互质的正整数的个数
思路: 先求出 n 大于等于 m 的因子 y ,再计算 n/y 的欧拉函数,最后相加即可

*/
int euler(int n)
{
     int m=floor(sqrt(double(n))+0.5);
    int phi=n;
    for(int i=2;i<=m;++i)
        if(n%i==0)
        {
            phi=phi/i*(i-1);    //phi*(i-1)/i是整数,而gcd(i-1,i)=0,所以i可以整除phi
            while(n%i==0)
                n/=i;
            if(n==1)
                break;
        }
        if(n>1)
            phi=phi/n*(n-1);
        return phi;
}
int main()
{
   int casen;
   cin>>casen;
   while(casen--)
   {
       int n,m;
       cin>>n>>m;
       int factor[1000000];
     if(n<m)
            cout<<"0\n";
        else if(n==m)
            cout<<"1\n";
        else if(m<=1)
            cout<<n<<endl;
            else
            {
                int tmp=0;
                for(int i=2;i*i<=n;i++)
              {
                  if(n%i==0&&i>=m)
                    factor[tmp++]=i;
                    if(n%i==0&&n/i>=m&&i*i!=n)
                    factor[tmp++]=n/i;
              }
               int s=1;
            for(int i=0;i<tmp;++i)
                s+=euler(n/factor[i]);
            cout<<s<<endl;

            }
   }
}                                 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值