GCD
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(2<=N<=1000000000, 1<=M<=N), 求1<=X<=N 且gcd(X,N)>=M的个数。
分析:
因为要求gcd(x,N)≥Mgcd(x,N)≥M
所以要让gcd尽量大,首先N是不能改变的而x小于N
那么必然有gcd(x,N)≤xgcd(x,N)≤x
所以我们只需要让gcd(x,N)=x就可以使得gcd最大gcd(x,N)=x就可以使得gcd最大
什么时候才有gcd(x,N)=xgcd(x,N)=x呢
很明显只有当x是N的因数的时候才行
现在我们已经有了一个大体的思路了,枚举N的因数,如果因数x≥Mx≥M那么我们就至少得到了一个满足题意的解
但是我们想知道除了gcd(x,N)=x≥Mgcd(x,N)=x≥M之外
是否还是其他小于等于N的数也k使得gcd(k,N)=x≥Mgcd(k,N)=x≥M
我们仍然观察gcd(x,N)=xgcd(x,N)=x其实可以写成gcd(x,x⋅Nx)=xgcd(x,x⋅Nx)=x
而我们希望找到一个数k使得gcd(k,N)=x≥Mgcd(k,N)=x≥M
即gcd(x⋅a,x⋅Nx)=x≥Mgcd(x⋅a,x⋅Nx)=x≥M
到这里我们便发现了
如果想要保持x⋅a和x⋅Nxx⋅a和x⋅Nx这两个数的最大公因数仍然是x不变
必须保证a和Nxa和Nx是互质的,而题目要求k必须小于N,所以a就必须是小于NxNx并且与其互质的数,这样的数有几个边有多少种解
这时我们知道了其实就是求NxNx的欧拉函数即可,然后累加起来便是答案
注意m为1的时候,N以内的任何数都可以,因为最大公因数最小为1,故直接输出n
code:
#include <bits/stdc++.h>
using namespace std;
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 * (n - 1);
}
return res;
}
void solve(int n,int m){
int s = 0;
if(m == 1) printf("%d\n",n);
else{
for(int i = 2; i * i <= n; i++){
if(n % i == 0){
if(i >= m) s += Euler(n/i);
if(i * i != n && n / i >= m) s += Euler(i);//注意判断完全平方数不要多加
}
}
printf("%d\n",s+1);
}
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,m;
scanf("%d%d",&n,&m);
solve(n,m);
}
return 0;
}