小M的区间公约数

Problem 75: 小M的区间公约数


Time Limit:1 Ms|  Memory Limit:10 MB
Difficulty:0

Description

小M对最大公约数已经很熟悉了,今天突发奇想,她想知道区间最大的公约数。两个数a,b,然后有n组询问,每组询问[L,R],输出[L,R]区间中a,b最大的公约数,没有输出-1。

Input

第一行输入a,b, (1 ≤ a, b ≤ 10^9)
第二行输入n,(1 ≤ n ≤ 10^4)
然后接下来n行,每行[L,R]。(1 ≤ L ≤ R ≤ 10^9)

Output

输出每次询问的结果。

Sample Input

9 27

1 5
10 11
9 11

Sample Output

3
-1

9

思路: a, b 的公约数也是a, b 最大公约数的约数, 所以直接求a, b最大公

约数的约数就行, 打个表水过, 注意10^9的约数个数才100个左右。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#define MAX 200

using namespace std;

int temp[MAX];

int gcd(int a, int b)                  //求 a, b 的最大公约数
{
	int res;
	while(b > 0)
	{
		res = a % b;
		a = b;
		b = res;
	}
	return a;
}

int fun(int m)
{
	int num = 0, i;
	for(i = 1; i < sqrt(m); i++)          //因为 > sqrt(m) 就重复了
	{
		if(m % i == 0)
		{
			temp[num++] = i;               //一大一小
			temp[num++] = m / i;          
		}
	}
	if(i == sqrt(m))                       //看看 sqrt(m) 是不是 m 的约数
	{
		temp[num++] = i;
	}
	return num;
}

bool cmp(int a, int b)
{
	return a > b;
}

int main()
{
	int a, b, n, i, j, start, end, cnt, t;
	scanf("%d%d%d", &a, &b, &n);
	cnt = fun(gcd(a, b));
	sort(temp, temp+cnt, cmp);             //从大到小排序
	for(i = 0; i < n; i++)
	{
		scanf("%d%d", &start, &end);
		/*if(start > end)                   //若首比尾大的话交换一下
		{
			t = start;                    
			start = end;
			end = t;
		}*/
		for(j = 0; j < cnt; j++)          //搜索所有约数, 在区间里的第一个就是最大的
		{
			if(temp[j] >= start && temp[j] <= end)
			{
				printf("%d\n", temp[j]);
				break;
			}
		}
		if(j == cnt)                       //没找到, 返回-1
		{
			printf("-1\n");
		}
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值