HDU - 5019 Revenge of GCD

题面

In mathematics, the greatest common divisor (gcd), also known as the greatest common factor (gcf), highest common factor (hcf), or greatest common measure (gcm), of two or more integers (when at least one of them is not zero), is the largest positive integer that divides the numbers without a remainder.
—Wikipedia

Today, GCD takes revenge on you. You have to figure out the k-th GCD of X and Y**.**

Input

The first line contains a single integer T, indicating the number of test cases.

Each test case only contains three integers X, Y and K.

[Technical Specification]

  1. 1 <= T <= 100
  2. 1 <= X, Y, K <= 1 000 000 000 000

Output

For each test case, output the k-th GCD of X and Y. If no such integer exists, output -1.

Sample Input

3
2 3 1
2 3 2
8 16 3

Sample Output

1
-1
2
Time limitMemory limitOS
1000 ms32768 kBWindows

题目大意

给定两个数x,y,要求求x,y的第k大公因数。

题目分析

既然这道题目和GCD有关,那么我们先不妨往GCD的方向先考虑

我们知道,x,y的公因数的所有因数也是x,y的公因数。所以我们不妨考虑最大公因数g,他的所有因数囊括了x,y的所有公因数。所有我们只有求出最大公因数g,再求出它的第k大因数即可。

求g的第k大因数,我们自然而然地想到了枚举每一个因数。但是,由于x,y的最大取值是1e12,所以,g的最大取值也是1e12(考虑x = y = 1e12)。一个个枚举到1e12自然是会T的。但是,由于g的因数总是等数量地分布在 g \sqrt g g 左右,所以我们只需要枚举到1e6就可以了。剩下的直接拿g除以前面的因数就可以得出后面的因数了。最后排个序就行了。(其实可以不用排序的,先循环出 g \sqrt g g 前的因数,在循环出后面的因数即可,这样更快)。

这里犯了一个错误,就是枚举的终止条件是i * i <= g,然后g的最大是1e12,自然是用long long存,但是i手癌写成了int,导致相乘以后依然是int,直接爆掉,T了好多次……这里一定要用long long的i,数据类型的事一定得要注意。

而且我发现用库自带的__gcd和我自己写的gcd,库的要比我快15ms……算了,下次直接用库吧,我也懒得写gcd了。__gcd在algorithm头文件里。

还有就是G++递交的运行速度会更快……真是个神奇的东西

代码

#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 1e6;
ll a[MAXN];
ll gcd(ll a, ll b){
  return b? gcd(b, a % b): a;
}
bool cmp(ll a, ll b){
  return a > b;
}
int main(int argc, char const *argv[]) {
  int T;
  scanf("%d", &T);
  while(T--){
    ll x, y, k;
    scanf("%lld%lld%lld", &x, &y, &k);
    ll g = gcd(x, y), cnt = 0;
    for(ll i = 1; i * i <= g; i++){
      if(g % i == 0){
        a[cnt++] = i;
        if(g != i * i)
          a[cnt++] = g / i;
      }
    }
    if(cnt < k)
      printf("%d\n", -1);
    else{
      sort(a, a + cnt, cmp);
      printf("%lld\n", a[k - 1]);
    }
  }
  return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值