HDU5019Revenge of GCD

来源:互联网 发布:网络视频广告 编辑:程序博客网 时间:2024/09/21 13:50

Revenge of GCD

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2588    Accepted Submission(s): 736


Problem 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
32 3 12 3 28 16 3
 

Sample Output
1-12

题意:给两个数x和y,求这两个数的第k大公约数,如果不存在就输出-1.

解析:根据给的数据大小分析一下,开个平方的话应该可以不超时。所以先求出x和y的最大公约数z,然后求这个数z的约数,存在数组中。需要第几个输出即可。

代码:

#include <stdio.h>#include <string.h>#include <math.h>#include <stack>using namespace std;typedef long long ll;#define N 1000005ll a[N], b[N]; ll gcd(ll x, ll y){return y == 0? x : gcd(y, x%y);}int main(){int t;ll x, y, k;scanf("%d", &t);while(t--){scanf("%lld%lld%lld", &x, &y, &k);if(k > x || k > y){puts("-1");continue;}ll z = gcd(x, y);ll s = sqrt(z);int cnt = 0, tol;for(ll i = 1; i <= s; i++){if(z % i == 0){a[cnt] = i;b[cnt] = z / i;cnt ++;}}tol = cnt * 2;if(s*s == z){tol --;b[cnt++] = s;}if(k > tol)puts("-1");else{if(k <= cnt)printf("%lld\n", b[k-1]);elseprintf("%lld\n", a[tol-k]);}}return 0;}



原创粉丝点击