coprime Sequence

Do you know what is called ``Coprime Sequence''? That is a sequence consists of nn positive integers, and the GCD (Greatest Common Divisor) of them is equal to 1.
``Coprime Sequence'' is easy to find because of its restriction. But we can try to maximize the GCD of these integers by removing exactly one integer. Now given a sequence, please maximize the GCD of its elements.

InputThe first line of the input contains an integer T(1T10)T(1≤T≤10), denoting the number of test cases.
In each test case, there is an integer n(3n100000)n(3≤n≤100000) in the first line, denoting the number of integers in the sequence.
Then the following line consists of nn integers a1,a2,...,an(1ai109)a1,a2,...,an(1≤ai≤109), denoting the elements in the sequence.
OutputFor each test case, print a single line containing a single integer, denoting the maximum GCD.Sample Input

3
3
1 1 1
5
2 2 2 3 2
4
1 2 4 8

Sample Output

1
2
2
题解:有n个数,通过删除一个数后使他们的最大公约数最大。这(n-1)个数的最大公约数必定是最小的两个数的因子之一。
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<stdlib.h>
 4 #include<stdio.h>
 5 #include<string.h>
 6 #include<math.h>
 7 #include<map>
 8 using namespace std;
 9 map<int,int>::iterator it;
10 int main()
11 {
12     int T;
13     scanf("%d",&T);
14     while(T--)
15     {
16        int n,x=0,t=0,i,j,a[100001],ans=1,l=2;
17        scanf("%d",&n);map<int,int>mp;
18        mp.clear();
19        for(i=0;i<n;i++)
20        {
21            scanf("%d",&a[i]);
22            if(a[i]==1)
23                x++;
24        }
25        if(x>=2)
26            printf("1\n");
27         else
28         {
29             sort(a,a+n);
30             while(l--)
31             {
32             for(i=1;i<=sqrt(a[l]);i++)
33             {
34                 if(a[l]%i==0)
35                 {
36                   mp[i]++;
37                   if(i*i!=a[l])
38                   mp[a[l]/i]++;
39 
40                 }
41             }
42             }
43             for(i=2;i<n;i++)
44               for(it=mp.begin();it!=mp.end();it++)
45               {
46                     if(a[i]%(it->first)==0)
47                          it->second++;
48               }
49                for(it=mp.begin();it!=mp.end();it++)
50                    if(it->second==n-1)
51                        ans=max(ans,it->first);
52                        printf("%d\n",ans);
53             }
54     }
55     return 0;
56 }

猜你喜欢

转载自www.cnblogs.com/moomcake/p/8969412.html