hdoj-5019-Revenge of GCD

来源:互联网 发布:mac相册导入移动硬盘 编辑:程序博客网 时间:2024/05/18 03:32

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(a,b),若是没有则输出-1
这题其实做起来也很简单,数据虽然有1 000 000 000 000 这么大,数组怕是gg了,但是vector足够存得下来了,然后就开始暴力就好了

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<vector>using namespace std;typedef long long ll;vector<ll>v;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--)    {        v.clear();        ll x,y,k;        scanf("%lld%lld%lld",&x,&y,&k);        ll val=gcd(x,y);        v.push_back(1);        if(val!=1) v.push_back(val);        for(ll i=2;i*i<=val;i++)        {            if(val%i==0)            {                v.push_back(i);                ll w=(ll)val/i;                v.push_back(w);            }        }        sort(v.begin(),v.end());        if(k>v.size())        printf("-1\n");        else printf("%I64d\n",v[v.size()-k]);    }    return 0;}
0 0
原创粉丝点击