Modified GCD

http://codeforces.com/problemset/problem/75/C
C. Modified GCD
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

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).

Output

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.

Sample test(s)
input
9 27
3
1 5
10 11
9 11
output
3
-1
9
题目大意:求a,b 在区间low-high的最大公约数(包括1比如a=1,b=2,low=1,high=3,那么结果为1)有人把这题划分到二分。不过做的时候也没用到二分啊。
解题思路:(之前做了几次都是在第11个测试超时,后来上网找了下答案,学习了很多;其中有个求某数 的因数的方法挺好。)           找到a,b的最大公约数m(gcd)然后枚举m的因素(即约数)保存到数组中,然后逆序查找满足在区间low-high的约数即为答案

#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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值