Pie or die
Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d& %I64u
SubmitStatus
Description
Well, here is another math class task. In mathematics, GCD is the greatestcommon divisor, and it's an easy task to calculate the GCD between two positiveintegers.
A common divisor for two positive numbers is a number which both numbersare divisible by.
But your teacher wants to give you a harder task, in this task you have tofind the greatest common divisord between two integers a and bthat is in a given range fromlow 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 nqueries. Each query is a range from low tohigh and you have toanswer each query.
Input
The first line contains two integersa and b, the twointegers as described above (1 ≤ a, b ≤ 109).The second line contains one integern, the number of queries (1 ≤ n ≤ 104). Then nlines follow, each line contains one query consisting of two integers,lowand high (1 ≤ low ≤ high ≤ 109).
Output
Print n lines. The i-th of them should contain the result ofthei-th query in the input. If there is no common divisor in the givenrange for any query, you should print -1 as a result for this query.
Sample Input
Input
9 27
3
1 5
10 11
9 11
Output
3
-1
9
题目分析:
输入两个整数,再输入一个范围,求在该范围内,两
整数最大公约数在这个范围内的最大约数。
解题思路:
1. 先利用欧拉函数求出两整数最大公约数。
2. 求出最大公约数的约数存入数组。
3. 快排。
4. 由大到小区间内查找。
#include <algorithm>
#include <iostream>
#include <cstdio>
using namespace std;
const int M = 1e6;
int ma[M];
int Gcd(int a, int b)
{
return b == 0 ? a : Gcd(b, a % b);
}
int main()
{
int a,b,n,ua,ub;
while(~scanf("%d %d",&a,&b))
{
scanf("%d",&n);
int ans = Gcd(a,b), to = 0;
for(int i = 1; i * i <= ans; i++)
{
if(ans % i == 0)
{
ma[to++] = i;
if(i * i != ans) ma[to++] = ans / i;
}
}
sort(ma,ma + to);
while(n--)
{ int sum=to;
int c=0,t;
scanf("%d %d",&ua,&ub);
if(ua>ub)
{
t=ua;
ua=ub;ub=t;
}
for(int i=to-1;i>=0;i--)
{
if(ma[i]<=ub&&ma[i]>=ua)
{printf("%d\n",ma[i]);
c=1;
break;}
}
if(c==0)
printf("-1\n");
}
}
return 0;
}