自爆魂

博客园 首页 新随笔 联系 订阅 管理

http://acm.hdu.edu.cn/showproblem.php?pid=5019

给出X 和Y,求出第K 大的 X 和Y 的公约数。

暴力求出所有公约数

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include<set>
#include <iostream>
#include <algorithm>
using namespace std;
#define RD(x) scanf("%d",&x)
#define RD2(x,y) scanf("%d%d",&x,&y)
#define clr0(x) memset(x,0,sizeof(x))
typedef long long LL;
LL gcd(LL a,LL b){    return b == 0? a:gcd(b,a%b);}
LL x,y,k;
LL p[1000005];
LL cmp(LL a,LL b)
{
    return a > b;
}
int main() {
    int _;
    RD(_);
    while(_--){
        int cnt = 0;
        scanf("%I64d%I64d%I64d",&x,&y,&k);
        LL op = gcd(x,y);
        for(LL i = 1;i < (int)sqrt(op)+1;++i){
            if(op%i == 0){
                p[cnt++] = i;
                if(i*i != op){
                    p[cnt++] = op/i;
                }
            }
        }//cout<<cnt;
        sort(p,p+cnt,cmp);
        if(cnt < k){
            puts("-1");
        }
        else{
            printf("%I64d\n",p[k-1]);
        }
    }

    return 0;
}


posted on 2014-10-15 18:27  自爆魂  阅读(145)  评论(0编辑  收藏  举报