设为首页 加入收藏

TOP

C. Modified GCD(二分加搜索约数)
2015-07-20 17:37:14 来源: 作者: 【 】 浏览:3
Tags:Modified GCD 二分 搜索

C. Modified GCD

time limit per test 2 seconds

memory limit per test 256 megabytes


题目连接: 传送门

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 divisord between two integers a and b that 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 n queries. Each query is a range from low tohigh 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). Thenn lines follow, each line contains one query consisting of two integers,low and high (1?≤?low?≤?high?≤?109).

Output

Print n lines. Thei-th of them should contain the result of thei-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

AC代码:

#include 
   
    
#include 
    
      #include 
     
       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++) //运用求素数的方法sqrt时间复杂度找出所有约数; { if(ans % i == 0) { ma[to++] = i; if(i * i != ans) ma[to++] = ans / i; } } sort(ma,ma + to); while(n--) { scanf("%d %d",&ua,&ub); int tp = lower_bound(ma, ma + to, ub) - ma; if(ma[tp] > ub || tp == to) tp--; if(ma[tp] < ua || ma[tp] > ub) puts("-1"); else printf("%d\n",ma[tp]); } } return 0; } 
     
    
   


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 5025 BFS+状压 下一篇2014北京网络预选赛1008(线段树..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·PostgreSQL 索引 - (2025-12-25 22:20:43)
·MySQL Node.js 连接 (2025-12-25 22:20:41)
·SQL 撤销索引、表以 (2025-12-25 22:20:38)
·Linux系统简介 (2025-12-25 21:55:25)
·Linux安装MySQL过程 (2025-12-25 21:55:22)