zoukankan      html  css  js  c++  java
  • Modified GCD CodeForces

    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 and b 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 integer n, 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.

    Example

    Input
    9 27
    3
    1 5
    10 11
    9 11
    Output
    3
    -1
    9

    题解:找出a,b的所有公共约数,然后二分查找区间左右端点的位置,分类讨论
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 
     4 const int maxn=2e5+10;
     5 
     6 int a,b,n;
     7 int ma[maxn];
     8 
     9 int gcd(int a,int b){
    10     if(b==0) return a;
    11     return gcd(b,a%b);
    12 }
    13 
    14 int main()
    15 {   cin>>a>>b>>n;
    16     int g=gcd(a,b),cnt=0;
    17     for(int j=1;j<=sqrt(g)+1;j++){
    18         if(g%j!=0) continue;
    19         ma[cnt++]=j;
    20         if(j<g/j) ma[cnt++]=g/j;
    21     }
    22     sort(ma,ma+cnt);
    23     int aa,bb;
    24     for(int i=1;i<=n;i++){
    25         cin>>aa>>bb;
    26         //for(int j=0;j<cnt;j++) cout<<ma[j]<<endl;
    27         int pos1=lower_bound(ma,ma+cnt,aa)-ma;
    28         int pos2=lower_bound(ma,ma+cnt,bb)-ma;
    29         //cout<<pos1<<" "<<pos2<<endl;
    30         if(pos1==pos2){
    31             if(ma[pos2]==bb) cout<<bb<<endl;
    32             else cout<<"-1"<<endl;
    33         }
    34         else{
    35             if(ma[pos2]==bb) cout<<ma[pos2]<<endl;
    36             else cout<<ma[pos2-1]<<endl;
    37         }
    38     }
    39     return 0;
    40 }
  • 相关阅读:
    Stanford coursera Andrew Ng 机器学习课程编程作业(Exercise 2)及总结
    zookeeper Eclipse 开发环境搭建及简单示例
    PHP语言基础之MySql 05 By ACReaper
    【读书笔记】并发编程需要注意的几个典型问题
    Eclipse安装SVN
    html学习
    某浪PHP面试题及答案优化
    《卡特教练》观后感
    [Usaco2006 Nov]Roadblocks第二短路
    std::vector 两种操作的比较
  • 原文地址:https://www.cnblogs.com/zgglj-com/p/7707411.html
Copyright © 2011-2022 走看看