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;
}