Greatest Greatest Common Divisor(技巧枚举)

499. Greatest Greatest Common Divisor
Time limit per test: 0.5 second(s)
Memory limit: 262144 kilobytes
input: standard
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. 

Input

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

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. 

Example(s)
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;
        }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值