HDU 2588 GCD && GCD问题总结

本文探讨了两个关于最大公约数(GCD)的问题。第一个问题是找出在1到N范围内满足GCD(X,N)≥M的整数X的数量;第二个问题是求解在1到N范围内能使GCD(X,N)≥M的所有X与N的最大公约数之和。通过运用欧拉函数和N的因子特性,提出了高效的算法解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

 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.

   求满足题目要求的x个数。

算法:

   直接筛选会超时,根据题目给出的不等式特点GCD(x,N) >= M 可以知道满足题目要求的一定是N的因子而且必须大于等于M(想想为什么?解体关键)。所以,只要枚举N的大于等于M的因子就可以了。因为,在10^9内最多的因子数不超过30个。所以,总时间是O(30*loglogn)接近常数。

 

  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <cstdio>  
  4. #include <cstring>  
  5. #include <cmath>  
  6. using namespace std;  
  7.   
  8. typedef __int64 LL;  
  9. const int MOD = 1000000007;  
  10.   
  11. int euler_phi(int n){  
  12.     int k = (int)sqrt(n + 0.5);  
  13.     int ans = n;  
  14.     for(int i = 2;i <= k;++i) if(0 == n % i){  
  15.         ans = ans / i * (i - 1);  
  16.         while(0 == n % i) n /= i;  
  17.     }  
  18.   
  19.     if(n > 1) ans = ans / n * (n - 1);  
  20.     return ans;  
  21. }  
  22.   
  23. LL getFact(int n,int m){  
  24.     LL res = 0;  
  25.     int k = sqrt(n + 0.5);  
  26.     int tmp;  
  27.   
  28.     for(int i = 1;i <= k;++i){  
  29.         if(0 == n % i){  
  30.             tmp = n / i;  
  31.             if(i >= m) res += euler_phi(n / i);  
  32.             if(tmp >= m && i != tmp) res += euler_phi(n / tmp);  
  33.         }  
  34.     }  
  35.     return res;  
  36. }  
  37.   
  38.   
  39.   
  40. int main()  
  41. {  
  42.     int T,n,m;  
  43.     scanf("%d",&T);  
  44.     while(T--){  
  45.         scanf("%d%d",&n,&m);  
  46.   
  47.         if(n == 1 && m == 1){  
  48.             puts("1");  
  49.             continue;  
  50.         }  
  51.   
  52.         printf("%I64d\n",getFact(n,m));  
  53.     }  
  54.     return 0;  
  55. }  


 

  

                                GCD(二)

题目:

   给你一个数N,使得在1~N之间能够找到x使得x满足gcd( x ,  N  ) >= M,求解gcd(x,N)的和。

算法:

  由上题的知识可以知道,1...N的互质个数为欧拉函数值且其gcd只能是N的因子。所以,对于N = x * y。我们只要

求出x在y内的互质个数就好了,结果乘以x就是gcd = x的和了.

证明:

   SUM(gcd = x ) = 1*x + 2*x + 3*x ..... y*x

  所以,当gcd = x的时候只要求出y的欧拉函数值就好了。

 

而一个数的因子又可以在sqrt(N)内求出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值