E - Revenge of GCD(数论)

E - Revenge of GCD

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

题目描述:

给出x和y,求他们第k大的公约数。

分析:

因为其他公约数都是最大公约数的因子。先求出最大公约数,再分解出它的各个因子。数可能会比较大,我们要做的是让空间时间尽可能少。

因为因数是两两配对的,或者两个重复。那么就可以只求一半的。而且如果开一个大的数组,很容易超内存。可以使用队列存,动态使用空间,减小不必要的空间。

代码:

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
using namespace std;
typedef long long ll;
queue <int> q;
ll gcd(ll a,ll b)
{
    if(b==0) return a;
    return gcd(b,a%b);
}
int que(int x)
{
    while(x>1)
    {
        x--;
        q.pop();
    }
    return q.front();
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        ll x,y,k;
        scanf("%lld%lld%lld",&x,&y,&k);
        ll num=gcd(x,y);
        if(num==1)
        {
            if(k==1) printf("1\n");
            else printf("-1\n");
        }
        else
        {
            ll posi=0;
            int end=sqrt(num);
            q=queue<int>();
            for(int i=1;i<=end;i++)
            {
                if(num%i==0)
                {
                    q.push(i);
                    posi++; 
                }
            }
            if(k>posi*2)
            {
                printf("-1\n");
            }
            else
            {
                if(k>posi)
                {
                    printf("%lld\n",que(2*posi-k+1));
                }
                else
                {
                    printf("%lld\n",num/que(k));
                }
            }
        }
        
    }
    return 0;
}
​

 

 

posted on 2020-01-22 20:44  Aminers  阅读(206)  评论(0编辑  收藏  举报

导航