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;
}

猜你喜欢

转载自blog.csdn.net/zvenWang/article/details/81186148