HDU 5019 Revenge of GCD

来源:互联网 发布:2017网络暴力的新闻 编辑:程序博客网 时间:2024/06/08 07:41
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
32 3 12 3 28 16 3
Sample Output
1-1

2

很简单的题目,先找到最大公因子,然后从它遍历到根下它,找到所有的因子,然后排序,比较所要求的个数。

(但是有一点特别怪异,思索一晚上也不明白为什么,根号下1e12最大才是1e6,不会超出int,但是从小到大排序的话比较函数用int就能过,从大到小排序的话就会WA,我提交了一晚上也没弄明白,因为这个问题WA了好多发)

#include<stdio.h>#include<math.h>#include<string.h>#include<stdlib.h>#include<algorithm>#include<iostream>using namespace std;long long c[10000005];bool cmp(long long a,long long b)//若从小到大排序的话不需要该函数 {//如果从大到小排序参数为int的话会WA,切记 return a>b;}long long gcd(long long a,long long b){return b==0?a:gcd(b,a%b);}int main(){long long  m;cin >> m;while(m--){long long a,b,k,temp1,temp,res; scanf("%lld%lld%lld",&a,&b,&k); temp=gcd(a,b);temp1=sqrt(temp);long long num=0;for(long long i=1;i<=temp1;i++){if(temp%i==0){c[num++]=i;if(i*i != temp)c[num++]=temp/i;}}if(num<k)printf("-1\n");else{sort(c,c+num,cmp);//从小到大排序的话,直接sort(c,c+num); printf("%lld\n",c[k-1]);//从小到大排序,输出则改为 1. printf("%lld\n",c[num-k]);   2.printf("%lld\n",temp/c[k-1]); }//即用最大公因子除以它得到相对应的数 }return 0;}


原创粉丝点击