Do you know what is called ``Coprime Sequence''? That is a sequence consists of nnpositive 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.
Input
The first line of the input contains an integer T(1≤T≤10)T(1≤T≤10), denoting the number of test cases.
In each test case, there is an integer n(3≤n≤100000)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(1≤ai≤109)a1,a2,...,an(1≤ai≤109), denoting the elements in the sequence.
Output
For 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
题意:几个数删除其中一个以获得最大的gcd。直接暴力肯定gg。。思路是正着求出一个记录每次gcd的 z[ ] 数组,在倒着求出一个记录每次gcd的 d[ ] 数组.
以 1 2 4 8为例
正着得到1 1 1 1
反着得到1 2 4 8
假设删除原数组中的2,那么就要求出正数组中第一个 1 与倒数组 4 的gcd并与当前的ans比较取较大值。详细解读可以参照代码
code:
#include<iostream>
using namespace std;
int gcd(int a ,int b){
return b?gcd(b,a%b):a;
}
int z[100005];
int d[100005];
int a[100005];
int main()
{
int t,n,Gcd;
cin>>t;
while(t--){
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
z[0]=a[0];
for(int i=1;i<n;i++){
z[i]=gcd(a[i],z[i-1]);//正着求gcd 比如 1 2 4 8-->1 1 1 1
Gcd=z[i];//记录n个数最终的gcd
}
d[n-1]=a[n-1];
for(int i=n-2;i>=0;i--){
d[i]=gcd(d[i+1],a[i]);//倒着求gcd 比如 1 2 4 8 -->1 2 4 8(反着得到的,先有8->4->2->1)
}
//int ans=d[1]; 也可以过
int ans=max(d[1],Gcd); //删除第一个得到的ans
for(int i=1;i<n;i++){
ans=max(ans,gcd(z[i-1],d[i+1]));//从第二个开始删除,每次保存新的gcd与ans中的较大者
}
cout<<ans<<endl;
}
}