CodeForces 75C(最大公约数)

来源:互联网 发布:达州网络人才网 编辑:程序博客网 时间:2024/05/18 16:17

CodeForces 75C(最大公约数)

  1. 题目链接
  2. 题目大意:给a和b,求n次a和b在low和high之间的最大公约数
  3. 解题思路:先求出a和b的最大公约数c,a和b的公约数一定是c的因数,枚举c的因数存在一个数组里,将数组排序求第一个大于high的因数的前一个因数,将其与low比较求第一个大于或者等于某数的时候要想到upper_bound 和low_bound
  4. 代码
#include<stdio.h>#include<string.h>#include<algorithm>#include<math.h>using namespace std;int ans[1000000];int gcd(int a,int b){        if(b==0)        return a;        return gcd(b,a%b);}int main(){        int a,b,c,i,j,n,low,high,cnt=0;        scanf("%d%d%d",&a,&b,&n);        c=gcd(a,b);        for(i=1;i*i<=c;i++)        {                if(c%i==0)                {                        ans[cnt++]=i;                        ans[cnt++]=c/i;                }        }        sort(ans,ans+cnt);        for(i=0;i<n;i++)        {                int t;                scanf("%d%d",&low,&high);                t=upper_bound(ans,ans+cnt,high)-ans-1;                if(ans[t]<low)                printf("-1\n");                else                printf("%d\n",ans[t]);        }        return 0;}
原创粉丝点击