HDU 5019 - Revenge of GCD

本文介绍了一种高效算法,用于查找两个给定整数的最大公约数的第k大因子,若不存在则输出-1。通过分解最大公约数并筛选其因子来实现。

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

题意

找出两个数的第k大公约数,如果不存在输出-1

思路

就是找最大公约数的第k大因子。

代码

  1. #include <cstdio>
  2. #include <algorithm>
  3. #include <functional>
  4. #include <stack>
  5. #include <set>
  6. #include <iostream>
  7. #include <string>
  8. #include <vector>
  9. #include <queue>
  10. #include <cstring>
  11. #include <string>
  12. #include <sstream>
  13. #include <map>
  14. #include <cmath>
  15. #define LL long long
  16. #define lowbit(x) ((x) & (-x))
  17. #define MP(a, b) make_pair(a, b)
  18. #define MS(arr, num) memset(arr, num, sizeof(arr))
  19. #define PB push_back
  20. #define ROP freopen("input.txt", "r", stdin);
  21. const double PI = acos(-1.0);
  22. const int INF = 0x3f3f3f3f;
  23. using namespace std;
  24. const int MAXN = 1000 + 5;
  25. int cnt;
  26. vector<LL> ve;
  27. int main()
  28. {
  29. //ROP;
  30. int T;
  31. cin >> T;
  32. while (T--)
  33. {
  34. ve.clear();
  35. LL a, b, k;
  36. cin >> a >> b >> k;
  37. LL ans = __gcd(a, b);
  38. ve.push_back(1ll);
  39. if (ans != 1) ve.push_back(ans);
  40. for (LL i = 2; i <= (LL)sqrt(ans * 1.0); i++)
  41. {
  42. int t = ans % i;
  43. if (t == 0)
  44. {
  45. ve.PB(i);
  46. if (ans / i != i) ve.PB(ans / i);
  47. }
  48. }
  49. if (k > ve.size()) cout << "-1" << endl;
  50. else
  51. {
  52. nth_element(ve.begin(), ve.begin() + k - 1, ve.end(), greater<LL>());
  53. cout << ve[k - 1] << endl;
  54. }
  55. }
  56. return 0;
  57. }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值