Pie or die(欧拉函数,求最大公约数)

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值