求第k大的gcd ,一定是gcd的因数,可以利用sqrt(n)的算法求出,然后再进行排序即可o(1)的查询

注意i要用LL,要不然会溢出,wrong了无数次

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

typedef __int64 LL;

LL gcd ( LL a , LL b )
{
    if ( b == 0 ) return a;
    return gcd ( b , a%b );
}

int main ( )
{
    int t;
    LL a , b , c;
    scanf ( "%d" , &t );
    vector<LL> v;
    while ( t-- )
    {
        v.clear ( );
        scanf ( "%I64d%I64d%I64d" , &a , &b , &c );
        LL temp = gcd ( a , b );
        for ( LL i = 1 ; i*i <= temp ; ++i )
        {
            if ( temp%i == 0 )
            {
                v.push_back ( i );
                if ( temp != i*i ) 
                    v.push_back ( temp/i );
            }
        }
        sort ( v.begin() , v.end());
        if ( c <= v.size( ) )
             printf ( "%I64d\n" , v[v.size()-c] );
        else printf ( "-1\n" );
    }
    return 0;
}