Revenge of GCD//HDU - 5019//数论

Revenge of GCD//HDU - 5019//数论


题目

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大的公约数
    链接:https://vjudge.net/contest/351853#problem/E

思路

最大公约数第k大的因子

代码

#include <iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
using namespace std;
long long x[1000];
bool cmp(long long a,long long b){
    return a>b;
}
long long gcd(long long a, long long b)
{
    if(b==0) return a;
    else return gcd(b,a%b);
}

int main(){
    int t;
    long long a,b,k;
    scanf("%d",&t);
    while(t--){
        memset(x,0,sizeof(x));
        cin>>a>>b>>k;
        long long d =gcd(a,b);
        long long i,cnt=0;
        for(i=1; i*i<=d;++i){
            if(d%i== 0){
                x[cnt++]=i;
                if(i*i!= d)
                    x[cnt++]=d/i;
            }
        }
        if(cnt<k)
            cout<<"-1"<<endl;
        else{
            sort(x, x+cnt,cmp);
            cout<<x[k-1]<<endl;
        }
    }
    return 0;
}

注意

所有类型记得用long long

发布了24 篇原创文章 · 获赞 9 · 访问量 466

猜你喜欢

转载自blog.csdn.net/salty_fishman/article/details/104011671