『算法-ACM竞赛-数学-数论』HDU 5019 revenge of GCD

『算法-ACM 竞赛-数学-数论』HDU 5019 revenge of GCD

Revenge of GCD

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
3 2 3 1 2 3 2 8 16 3

Sample Output
1 -1 2

for 循环暴力求即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
long long x[500000], a, b, k;
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
memset(x, 0, sizeof(x));
scanf("%lld%lld%lld", &a, &b, &k);
long long d = __gcd(a, b);
long long i, j = 0;
for (i = 1; i * i <= d; ++i)
{
if (d % i == 0)
{
x[j++] = i;
if (i * i != d)
x[j++] = d / i;
}
}

if (j < k)
{
printf("-1\n");
}
else
{
sort(x, x + j);
printf("%lld\n", x[j - k]);
}
}
return 0;
}

『算法-ACM竞赛-数学-数论』HDU 5019 revenge of GCD
https://chiamzhang.github.io/2024/06/29/『算法-ACM竞赛-数学-数论』HDU 5019 revenge of GCD/
Author
Chiam
Posted on
June 29, 2024
Licensed under