南邮 OJ 1126 GCD
2015-08-05 09:11
155 查看
GCD
时间限制(普通/Java) : 2000 MS/ 6000 MS 运行内存限制 : 65536 KByte总提交 : 141 测试通过 : 23
比赛描述
The greatest common divisor GCD(a,b) of two positive integer a and b,sometimes written (a,b),
is the largest divisior 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 difficlut problem.
Given integer N and M,how many integer X satisfies 1<=X<=N and (X,N)≥M.
输入
The first line or input is an integer 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.
输出
For each test case,output the answer on a single line.
样例输入
3
1 1
10 2
10000 72
样例输出
1
6
260
题目来源
第九届中山大学程序设计竞赛预选题
/*
题意:求有多少x(1<=x<=n),使得gcd(x,n)>=m;
先求n的所有大于等于m的因子,ei
答案ans=∑phi[n/ei];phi[i]为欧拉函数,为不大于i且与i互质的正整数个数
why?
对于一个与ei互质且小于等于n/ei的正整数p来说,p*ei<=n,gcd(p*ei,n)=ei;
则phi[n/ei]就是1~n中的与n最大公约数是ei的个数。而n与1~n的最大公约数必定是n的因子。
所以符合gcd(x,n)>=m的x为n所有大于等于m因子的倍数,用phi即可避免重复。
*/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=1000;
int e[maxn];
int euler_phi(int n)
{
int m=(int)sqrt(n+0.5);
int ans=n,i;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
ans=ans/i*(i-1);
while(n%i==0)n/=i;
}
}
if(n>1)ans=ans/n*(n-1);
return ans;
}
int main()
{
int T,n,m;
cin>>T;
while(T--)
{
cin>>n>>m;
int i,j,k,t=0,num,ans=0;
num=(int)sqrt(n+0.5);
for(i=1;i<num;i++)
{
if(n%i==0)
{
if(i>=m)e[t++]=n/i;
if(n/i>=m)e[t++]=i;
}
}
if(num*num==n&&num>=m)e[t++]=num;
for(i=0;i<t;i++)
ans+=euler_phi(e[i]);
cout<<ans<<endl;
}
return 0;
}