Description
给出两个整数 a,b ,每次查询给出一个区间 [L,R] ,问 a,b 的介于该区间的最大公因子 d
* Input*
第一行两个整数
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
的因子,预处理出
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;
}