499. Greatest Greatest Common Divisor
Memory limit: 262144 kilobytes
output: standard
Andrew has just made a breakthrough in sociology: he realized how to predict whether two persons will be good friends or not. It turns out that each person has an innerfriendship number (a positive integer). And the quality of friendship between two persons is equal to the greatest common divisor of their friendship number. That means there are prime people (with a prime friendship number) who just can't find a good friend, andWait, this is irrelevant to this problem. You are given a list of friendship numbers for several people. Find the highest possible quality of friendship among all pairs of given people.
The first line of the input file contains an integer n () — the number of people to process. The next n lines contain one integer each, between 1 and
(inclusive), the friendship numbers of the given people. All given friendship numbers are distinct.
Output one integer — the highest possible quality of friendship. In other words, output the greatest greatest common divisor among all pairs of given friendship numbers.
sample input | sample output |
4 9 15 25 16 | 5
|
题意:
给出 N(2 ~ 100000)个数 ,后给出这 N 个不同的数(1 ~ 1000000),任意一对数都存在一个最大公因子,求出所有对中的最大的最大公因子数。
思路:
类似于素数筛选的方法,数最大也只是 1000000 ,给出的数任意两个之间是不会一样的,所以最大的公因子上限为 50000。同时用一个数组标记哪些数出现过,筛选的时候从上限开始往下限搜,当一搜到这个因子的倍方数出现两次的时候就马上跳出循环,这时候的公因子数即为答案。
AC:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX = 1000005;
int num[MAX];
int main() {
int n;
scanf("%d", &n);
memset(num, 0, sizeof(num));
while (n--) {
int ans;
scanf("%d", &ans);
num[ans] = 1;
}
int temp = 0;
for (int i = MAX / 2; i >= 1; --i) {
int sum = 0;
for (int j = i; j <= MAX; j += i) {
if (num[j]) ++sum;
if (sum == 2) {
printf("%d\n", i);
temp = 1;
break;
}
}
if (temp) break;
}
}