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)
第二行输入n,(1 ≤ n ≤ 10^4)
然后接下来n行,每行[L,R]。(1 ≤ L ≤ R ≤ 10^9)
Output
输出每次询问的结果。
Sample Input
9 27
3
1 5
10 11
9 11
3
1 5
10 11
9 11
Sample Output
3
-1
-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;
}