codeforces C. Modified GCD

传送
在这里插入图片描述
二分+数论
数论:
gcd(a,b)=公约数g1 *公约数g2 找两个数的所有公约数就可以转化成找最大公约数的约数

#include<bits/stdc++.h>	
#define ll long long 
using namespace std;
ll n;
ll r, l, mid;
ll gd;
ll c[100000 + 100];
ll a, b;
ll gcd(ll x, ll y)
{
	return x % y ? gcd(y, x % y) : y;	
}
int main()
{
	cin >> a >> b;
	gd = gcd(a, b);
	int k = 0;
	for (int i = 1; i <= (int)sqrt(gd); i++)//gcd(a,b)=公约数g1 *公约数g2    找两个数的所有公约数就可以转化成找最大公约数的约数
	{
		if (gd % i == 0)
		{
			c[++k] = i;
			if (gd / i != i)
				c[++k] = gd / i;

		}
	}
	sort(c + 1, c + 1 + k);
	/*
	for (int i = 1; i <= k; i++)
		cout << c[i] << " ";
	cout << endl;*/	
	ll n;
	cin >> n;
	while (n--)
	{
		ll low, high;
		cin >> low >> high;
		l = 1, r = k;
		ll ans = -1;
		while (l <= r)
		{
			mid = (l + r) >> 1;
		//	cout << "mid" << mid << endl;
			if (c[mid] < low)
				l = mid + 1;
			else if (c[mid] > high)
				r = mid - 1;
			else
			{
				ans = c[mid];
				l = mid + 1;
			}
		}
		cout << ans << endl;

	}
	return 0;

}

 
posted @ 2020-07-27 12:24  DuJunlong  阅读(8)  评论(0编辑  收藏  举报  来源