AcWing---公约数---最大公约数

4199. 公约数 - AcWing题库 

思路:

最大整数x一定是最大公约数的因数,所以先用__gcd(a,b)求出a和b的最大公因数,再用O(log(n))的算法求出最大公因数的因数,放到vector中,并将vector排序。利用STL中的upper_bound(res.begin(),res.end(),num)找到res中大于num的最小位置,如果该位置的元素大于等于l,则成立。

推荐博客:关于lower_bound( )和upper_bound( )的常见用法_lowerbound和upperbound-CSDN博客

for(auto i : v)遍历容器元素_for auto 遍历-CSDN博客

【C++】__gcd(x,y)函数_∑ y∈c gcd(x,y)-CSDN博客

C++代码:

#include<bits/stdc++.h>
using namespace std;

int a,b,q,l,r;
vector<int> res;
int main(){
    cin>>a>>b>>q;
    int temp=__gcd(a,b);
    for(int i=1;i*i<=temp;i++){
        if(temp%i==0){
            res.push_back(i);
            res.push_back(temp/i);
        }
    }
    sort(res.begin(),res.end());
    /*for(auto i:res){
        cout<<i<<' ';
    }
    cout<<endl;*/
    for(int i=1;i<=q;i++){
        cin>>l>>r;
        int idx=upper_bound(res.begin(),res.end(),r)-res.begin();//找大于r的最小索引(顺序)
        if(idx-1>=0 && res[idx-1]>=l){
            cout<<res[idx-1]<<endl;
        }
        else{
            cout<<"-1"<<endl;
        }
    }
    return 0;
}

Python代码:

在python中:Python3二分查找库函数bisect(), bisect_left()和bisect_right()介绍-CSDN博客

import math
import bisect
res=[]
a,b=map(int,input().split())
q=int(input())
temp=math.gcd(a,b)
j=1
while j*j<=temp:
    if temp%j==0:
        res.append(j)
        res.append(int(temp/j))
    j+=1
res.sort()
for i in range(1,q+1):
    l,r=map(int,input().split())
    idx=bisect.bisect_right(res,r)
    if idx-1>=0 and res[idx-1]>=l:
        print(res[idx-1])
    else:
        print("-1")

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值