HDU 5019 数论、公因数

 

Revenge of GCD

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 226    Accepted Submission(s): 66


 

Problem Description

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

 

题意很简单,就是求第k大的gcd,求出最大的公因子后,其他的公因子都是最大公因子的因数,很容易可以求出所有的公因数

但是要注意的是这个题的时间控制的很紧,稍微不注意就会超时,

比如说,一开始我图简单在求其他的公因数的时候循环停止的条件没控制好(如下图),就TMD超时了,

for(i=1; i<=d; ++i) //d是最大的公因数
        {
            if(d%i== 0)
                x[j++] = i;
        }

改进之后是这样的

for(i=1; i*i<=d; ++i)//每次循环把能整除最大公因数的除数和商都写入数组,最后进行排序即可
        {
            if(d%i== 0)
            {
                x[j++] = i;
                if(i*i != d)    x[j++] = d/i;
            }
        }

 

最后附上AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
 
using namespace std;
 
#define ll long long int
 
const int N = 1e5;
 
ll x[N], a, b, k;
 
ll gcd(ll a, ll b)
{
    if(b==0) return a;
    else return gcd(b,a%b);
}
 
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        memset(x, 0, sizeof(x));
        scanf("%lld%lld%lld", &a, &b, &k);
        ll d = gcd(a,b);
        ll i, j = 0;
        for(i=1; i*i<=d; ++i)
        {
            if(d%i== 0)
            {
                x[j++] = i;
                if(i*i != d)    x[j++] = d/i;
            }
        }
    
        if(j<k)
        {
            printf("-1\n");
 
        }
       else{
	    sort(x, x+j);
        printf("%lld\n", x[j-k]);
         }
    }
 
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值