题面
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 <= T <= 100
- 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
Time limit | Memory limit | OS |
---|---|---|
1000 ms | 32768 kB | Windows |
题目大意
给定两个数x,y,要求求x,y的第k大公因数。
题目分析
既然这道题目和GCD有关,那么我们先不妨往GCD的方向先考虑
我们知道,x,y的公因数的所有因数也是x,y的公因数。所以我们不妨考虑最大公因数g,他的所有因数囊括了x,y的所有公因数。所有我们只有求出最大公因数g,再求出它的第k大因数即可。
求g的第k大因数,我们自然而然地想到了枚举每一个因数。但是,由于x,y的最大取值是1e12,所以,g的最大取值也是1e12(考虑x = y = 1e12)。一个个枚举到1e12自然是会T的。但是,由于g的因数总是等数量地分布在 g \sqrt g g左右,所以我们只需要枚举到1e6就可以了。剩下的直接拿g除以前面的因数就可以得出后面的因数了。最后排个序就行了。(其实可以不用排序的,先循环出 g \sqrt g g 前的因数,在循环出后面的因数即可,这样更快)。
这里犯了一个错误,就是枚举的终止条件是i * i <= g,然后g的最大是1e12,自然是用long long存,但是i手癌写成了int,导致相乘以后依然是int,直接爆掉,T了好多次……这里一定要用long long的i,数据类型的事一定得要注意。
而且我发现用库自带的__gcd和我自己写的gcd,库的要比我快15ms……算了,下次直接用库吧,我也懒得写gcd了。__gcd在algorithm头文件里。
还有就是G++递交的运行速度会更快……真是个神奇的东西
代码
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 1e6;
ll a[MAXN];
ll gcd(ll a, ll b){
return b? gcd(b, a % b): a;
}
bool cmp(ll a, ll b){
return a > b;
}
int main(int argc, char const *argv[]) {
int T;
scanf("%d", &T);
while(T--){
ll x, y, k;
scanf("%lld%lld%lld", &x, &y, &k);
ll g = gcd(x, y), cnt = 0;
for(ll i = 1; i * i <= g; i++){
if(g % i == 0){
a[cnt++] = i;
if(g != i * i)
a[cnt++] = g / i;
}
}
if(cnt < k)
printf("%d\n", -1);
else{
sort(a, a + cnt, cmp);
printf("%lld\n", a[k - 1]);
}
}
return 0;
}