CodeForces 75 C.Modified GCD(数论)

Description

给出两个整数 a,b ,每次查询给出一个区间 [L,R] ,问 a,b 的介于该区间的最大公因子 d

* Input*

第一行两个整数a,b,之后输入一整数 q 表示查询数,每组查询输入两个整数L,R表示查询 a,b 的介于区间 [L,R] 的最大公因子 (1a,b109,1n10000,1LR109)

Output

对于每组用例,如果 a,b 没有介于 [L,R] 之间的公因子则输出 1 ,否则输出介于该区间的最大公因子

Sample Input

9 27
3
1 5
10 11
9 11

Sample Output

3
-1
9

Solution

a,b 的公因子即为其最大公因子 d 的因子,预处理出d的所有因子,每次二分查出公因子中不超过 R 的最大公因子,如果找不到或者小于L则无解,否则其为答案

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=10001;
int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}
int main()
{
    int a,b,c[maxn];
    while(~scanf("%d%d",&a,&b))
    {
        int d=gcd(a,b),n=0;
        for(int i=1;i*i<=d;i++)
            if(d%i==0)
            {
                c[n++]=i;
                if(i*i!=d)c[n++]=d/i;
            }
        sort(c,c+n);
        int q;
        scanf("%d",&q);
        while(q--)
        {
            int l,r;
            scanf("%d%d",&l,&r);
            int pos=upper_bound(c,c+n,r)-c-1;
            if(pos==-1||c[pos]<l)printf("-1\n");
            else printf("%d\n",c[pos]);
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值