Revenge of GCD // HDU - 5019 // Number Theory

Revenge of GCD // HDU - 5019 // Number Theory


topic

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

Thinking

The greatest common divisor k-th largest factor

Code

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

note

All types with long long remember

Published 24 original articles · won praise 9 · views 466

Guess you like

Origin blog.csdn.net/salty_fishman/article/details/104011671