CodeForces 75C Modified GCD

来源:互联网 发布:javascript var 编辑:程序博客网 时间:2024/05/17 21:56


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.

Examples
input
9 2731 510 119 11
output
3-19

题意:给你两个数,再给你一个范围,问是否在这个范围里存在这两个数的公约数。

思路:先用求出这两个数的最大公约数,然后求这个最大公约数的约数,再看范围内是否存在。

刚开始编译器出点故障一直没输出。。害的我半天不知道哪出问题了。无语。。。。。。

欧几里德算法的几种代码实现

递归法:

int gcd(int a,int b) {    if(b==0)         return a;     return          gcd(b,a%b); }
优化后
int gcd(int a,int b){    return b ? gcd(b,a%b) : a;
}
迭代形式
int Gcd(int a, int b)  {     while(b != 0)    {      int r = b;        b = a % b;        a = r;    }      return a; }


#include<stdio.h>#include<string.h>#include<math.h>#include<algorithm>using namespace std;int gcd(int a,int b){int m;while(a){m=b%a;b=a;a=m;    }    return b; } int main(){int a,b,n,i,j,l,k,num,low,high,ab[1100];while(scanf("%d%d",&a,&b)!=EOF){int ans=gcd(a,b);k=0;    for(i=1;i*i<=ans;i++)    {   if(ans%i==0)   {  ab[k++]=i;  if(i*i!=ans)  { ab[k++]=ans/i;  }   }    }    sort(ab,ab+k);        scanf("%d",&n);     while(n--)    {   int flag=0;   scanf("%d%d",&low,&high);   for(i=k-1;i>=0;i--)   {           if(ab[i]<=high&&ab[i]>=low)      {     printf("%d\n",ab[i]);     flag=1;     break;   }   }   if(flag==0)   printf("-1\n");   }}return 0;}


0 0
原创粉丝点击