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)≥M g c d ( x , N ) ≥ M
所以要让gcd尽量大,首先N是不能改变的而x小于N
那么必然有 gcd(x,N)≤x g c d ( x , N ) ≤ x
所以我们只需要让 gcd(x,N)=x就可以使得gcd最大 g c d ( x , N ) = x 就 可 以 使 得 g c d 最 大
什么时候才有 gcd(x,N)=x g c d ( x , N ) = x 呢
很明显只有当x是N的因数的时候才行
现在我们已经有了一个大体的思路了,枚举N的因数,如果因数 x≥M x ≥ M 那么我们就至少得到了一个满足题意的解
但是我们想知道除了 gcd(x,N)=x≥M g c d ( x , N ) = x ≥ M 之外
是否还是其他小于等于N的数也k使得 gcd(k,N)=x≥M g c d ( k , N ) = x ≥ M
我们仍然观察 gcd(x,N)=x g c d ( x , N ) = x 其实可以写成 gcd(x,x⋅Nx)=x g c d ( x , x ⋅ N x ) = x
而我们希望找到一个数k使得 gcd(k,N)=x≥M g c d ( k , N ) = x ≥ M
即 gcd(x⋅a,x⋅Nx)=x≥M g c d ( x ⋅ a , x ⋅ N x ) = x ≥ M
到这里我们便发现了
如果想要保持 x⋅a和x⋅Nx x ⋅ a 和 x ⋅ N x 这两个数的最大公因数仍然是x不变
必须保证 a和Nx a 和 N x 是互质的,而题目要求k必须小于N,所以a就必须是小于 Nx N x 并且与其互质的数,这样的数有几个边有多少种解
这时我们知道了其实就是求 Nx N x 的欧拉函数即可,然后累加起来便是答案
注意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;
}