hdu 5019 Revenge of GCD

主题链接:http://acm.hdu.edu.cn/showproblem.php?

pid=5019

题目大意:给出A。B两个数。求第k大的公约数,假设没有输出-1

思路:直接把A,B的公约数所有求出来,然后找出来即可啦,当时没有注意数据大小竟然是10^12,用的int 。所以果断错啦,赛完才发现,坑呀。

。。。。

注意要用long long或是__int64。。

。。

code:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>

using namespace std;

typedef __int64 LL;

LL gcd(LL a,LL b)
{
    LL r;
    while(b>0)
    {
         r=a%b;
         a=b;
         b=r;
    }
    return a;
}

bool cmp(LL a,LL b)
{
    return a>b;
}

LL f[100000];

int main()
{
    int T;
    LL x,y,k,i,len;
    scanf("%d",&T);
    while(T--)
    {
        len=0;
        scanf("%I64d%I64d%I64d",&x,&y,&k);
        LL r=gcd(x,y);
        LL d=sqrt(r);
        while(d*d<=r) d++;  //这个循环和接下来的那个循环能够不要不要。仅仅是以前写过一个代码是这么写过就这么写的
        while(d*d>r)  d--;
        for(i=1;i<=d;i++)
        {
            if(r%i==0)
            {
                if(i*i==r)
                {
                    f[len++]=i;
                }
                if(i*i<r)
                {
                    f[len++]=i;
                    f[len++]=r/i;
                }
            }
        }
        sort(f,f+len,cmp);

        if(len>=k)
        {
            printf("%I64d
",f[k-1]);
        }
        else
        {
            printf("-1
");
        }
    }
    return 0;
}


版权声明:本文博客原创文章。博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/hrhguanli/p/4664972.html