D - 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

最近在做数论,用暴力方法几乎都超时,但是又不会优化- -只能查 --。

这题就是输入俩数,然后然你找他俩第K大的公约数,思路就是,先找到最大公约数,然后找最大公约数的约数,把他们都放到队列里面然后sort一下就行了。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <cmath>
#include <list>
#include <queue>
#include <stack>
#include <map> 
#include <set>
using namespace std;
#define INF 0x3f3f3f3f
typedef long long ll;
ll gcd(ll x,ll y)
{
	if(y==0) return x;
	else{return gcd(y,x%y);
	}
}
/*void fun(int a)
{
	cout<<a<<endl;
}*/
int main()
{   ll T;
	cin>>T;
	ll a,b,k,i;
	vector<ll> vec; 
	
	while(T--)
	{
		cin>>a>>b>>k;
		vec.clear();
		ll d=gcd(min(a,b),max(a,b));
		vec.push_back(1);
		if(d!=1)
		{	vec.push_back(d);
			for( i=2;i<sqrt(d);i++)
			{	
				if(d%i==0)
				{
					vec.push_back(i);
					vec.push_back(d/i);
				}
			}
			if(i==sqrt(d)) vec.push_back(i);
		}
		sort(vec.begin(),vec.end());
		if(k>vec.size())
			printf("-1\n");
		else cout<<vec[vec.size()-k]<<endl;

	}
	return 0; 
}

猜你喜欢

转载自blog.csdn.net/qq_40941611/article/details/81185499
gcd