天天看點

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
           

題意:第一行輸入一個數t,表示有t組資料

第2到t+1行,每行輸入三個數,前兩個數是x和y,第3個數表示x,y的第k大公因子。

求x和y的第k大公因子,如果不存在輸出-1. 

思路:先用歐幾裡得算法算出x和y的最大公因數g。x和y的公因子都是g的因子。可以直接枚舉。

代碼如下:

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
#define ll long long
ll gcd(ll a,ll b)
{
    return b!=0?gcd(b,a%b):a;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll x,y,k,i,g;
        cin>>x>>y>>k;
        g=gcd(x,y);
        //printf("%lld\n",g);
        ll num=0,a;
        for(i=1;i*i<=g;i++)
        {
            if(g%i==0)
                {
                    num++;
                    a=g/i;
                }
            if(num==k)
                break;
        }
        if(num==k)printf("%lld\n",a);
        else
        {
        for(i=sqrt(g);i>=1;i--)
        {
            if(i*i==g)continue;
            if(g%i==0)
            {
                num++;
                a=i;
            }
            if(num==k)break;
        }
        if(num==k)printf("%lld\n",a);
        else
            printf("-1\n");
        }
    }
    return 0;
}
           

繼續閱讀