Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a andb that is in a given range from low to high (inclusive), i.e. low?≤?d?≤?high. It is possible that there is no common divisor in the given range.
You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query.
The first line contains two integers a and b, the two integers as described above (1?≤?a,?b?≤?109). The second line contains one integern, the number of queries (1?≤?n?≤?104). Then n lines follow, each line contains one query consisting of two integers, low and high (1?≤?low?≤?high?≤?109).
Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query.
9 27
3
1 5
10 11
9 11
3
-1
9
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<stdlib.h>
#include<iomanip>
#include<list>
#include<deque>
#include<map>
#include <stdio.h>
#include <queue>
#define maxn 10000+5
#define ull unsigned long long
#define ll long long
#define reP(i,n) for(i=1;i<=n;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define cle(a) memset(a,0,sizeof(a))
#define mod 90001
#define PI 3.141592657
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
bool cmp(int a,int b){
return a>b;
}
vector<int> x;
int low, high, a, b, n, m, ans,i;
int gcd(int c,int d)
{
return d==0?c:gcd(d,c%d);
}
int main() {
scanf("%d%d", &a, &b);
a = gcd(a, b);
b = sqrt(a);
x.clear();
int count=0;
for (i=1; i<=b; i++)
if (a % i == 0) {
x.push_back(i);
x.push_back(a/i);
}///求最大公约数的因数,并保存到x
sort(x.begin(), x.end());
int mark=0;
scanf("%d", &n);
for (i=0; i<n; i++) {
scanf("%d%d", &low, &high);
mark=0;
for(int i=x.size()-1;i>=0;i--)
if(x[i]<=high&&x[i]>=low){mark=1;ans=x[i];break;}
if(!mark)cout<<-1<<endl;
else cout<<ans<<endl;
}
return 0;
}