Bestcoder #10 hdoj5019

来源:互联网 发布:数控车凹圆弧编程实例 编辑:程序博客网 时间:2024/06/01 07:40

题目链接

题目描述

求AB的第K大公约数
这里写图片描述

思路

枚举AB所有公因子(O10^6

代码如下

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <cmath>using namespace std;const long long INF = 1000000000;long long  ans[1001000];long long  gcd(long long x, long long y){    if(y == 0) return x;    return gcd(y,x%y);}int main(){   int T;   scanf("%d",&T);   while(T--)   {      long long x,y,k;      scanf("%lld%lld%lld",&x,&y,&k);      if(x < y) swap(x,y);      long long g = gcd(x,y);      long long d = sqrt(g);      long long r = 0;     // memset(ans,INF,sizeof(ans));     int re = 0;      for(int i = 1; i<=d; i++)      {          if(g%i == 0)          {              ans[r++] = i;              long long ca = g/i;              if(ca != i) ans[r++] = ca;          }      }      sort(ans, ans+r);      if(k>r) printf("-1\n");      else printf("%lld\n",g/ans[k-1]);   }}
0 0