题目
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
题目大意
求a,b的第k大公约数。
解题思路
先求出a,b的最大公约数,最大公约数的第k大因数就是a,b的第k大公约数。
代码
#include <cstdio>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
int T;
long long a[1001010];
long long x,y,k,s,n;
long long gcd(long long a,long long b)
{
if (b==0) return a;
return gcd(b,a%b);
}
bool cmp(long long x,long long y)
{
return x<y;
}
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%lld%lld%lld",&x,&y,&k);
n=gcd(x,y);
s=0;
long long mx=sqrt(n);
for (int i=1;i<=mx;i++)
{
if (n%i==0)
{
long long t=n/i;
a[s++]=i;
if (t!=i) a[s++]=t;
}
}
if (k>s) printf("-1\n");
else
{
sort(a,a+s,cmp);
printf("%lld\n",n/a[k-1]);
}
}
return 0;
}