挂机水题日记 Cf - 75C

链接:http://codeforces.com/problemset/problem/75/C

题意:

给你两个数a ,b(1e9范围内),q个查询区间 [ l,  r],问你这些区间内能找到的 a 和 b 的公因子最大是多少。

思路:

水题,枚举 gcd 因子的时候开平方优化完就过了。

核心思路就是枚举 gcd (a, b) 的因子,用max维护一下,那么枚举的过程中,如果a,b 的 gcd 过大,那 O( gcd(a, b) )就 T定了,所以开平方优化以下,令 dd = __gcd(a, b),然后在 sqrt(dd)之前正常枚举,之后的因子用 dd 与之前枚举的因子做商,再排下序即可。

我的AC代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxx = 1e5 + 7;
const int Inf = 1 << 30;
int a, b;
int cas;
int l, r;
int pr[maxx]; //gcd因子

int main() {
	cin >> a >> b;
	
	//枚举gcd因子 + 平凡根优化复杂度
	int dd = __gcd(a, b);
	int t = 0;
	for(int i = 1; i <= sqrt(dd); i++) {
		if(dd % i == 0) pr[++t] = i;
	}
	int pos = t;
	for(int i = 1; i <= pos; i++) pr[++t] = dd / pr[i];
	sort(pr + 1, pr + t + 1);

	cin >> cas;
	while(cas--) {
		cin >> l >> r;
		bool flg = 0;
		int ans = 0;
		for(int i = 1; i <= t; i++) {
			if(pr[i] > r) break;
			else {
				if(pr[i] < l) continue;
				else {
					flg = 1;
					ans = max(ans, pr[i]);
				}
			}
		}
		if(!flg) puts("-1");
		else cout << ans << endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值