SGU 499:Greatest Greatest Common Divisor

Time Limit:1000MS    Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

Description

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 inner friendship 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, and Wait, 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.

Sample Input

sample input
sample output
4
9
15
25
16
5

//题意:找出n个数中某两个数的公约数的值最大。
//分析:直接暴力枚举时间复杂度O(n^2)是不允许的。题目中说明n个数的范围都在1000000以内,那么可以用一个数组
标记每个数据出现多少次。以最大的数据maxnum为上限开始枚举所有的数for(maxnum->1)的倍数,如果当前这个数
的倍数出现两次以上则得到最大公约数。整体时间复杂度约为10^6*(log(10^6)).
#include<stdio.h>
#include<string.h>
using namespace std;
#define maxn 1000005
#define max(p,q) (p>q?p:q)

int num[maxn],a[maxn];
int main()
{
	int n,i,j,k;
	while(~scanf("%d",&n))
	{
		int maxp=1,ans;
		memset(num,0,sizeof(num));
		for(i=1;i<=n;i++)
		{
			scanf("%d",&a[i]);
			maxp=max(maxp,a[i]);
			num[a[i]]++;
		}
		int flag=0;
		for(i=maxp;i>=1;i--)
		{
			k=0;
			for(j=i;j<=maxp;j+=i)
			{
				if(num[j])
					k+=num[j];
				if(k>1)
				{
					printf("%d\n",i);
					flag=1;
					break;
				}
			}
			if(flag)
				break;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值