题意:给出一个序列,这个序列所以数的最大公因数为1,要求去掉任意一个数,是这个序列所有数的最大公因数最大,输出这个最大公因数
思路:用两层for循环肯定会超时,我们可以用两个数组,left数组记录这个数(包括这个数)左边所有数的最大公因数,right数组同理,然后,去掉第i个数之后的所有数的最大公因数为gcd(left[i - 1],right[i + 1]),然后特判第一个位置和最后一个位置
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <cmath>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn = 100000+7 ;
int b[maxn];
int Left[maxn];
int Right[maxn];
int gcd(int a,int b)
{
int r;
while(b>0)
{
r=a%b;
a=b;
b=r;
}
return a;
}
int main(void){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
for(int i = 0; i < n; i++){
scanf("%d",&b[i]);
}
Left[0] = b[0];
for(int i = 1; i < n; i++){
Left[i] = gcd(Left[i - 1],b[i]);
}
Right[n - 1] = b[n - 1];
for(int i = n - 2; i >= 0; i--){
Right[i] = gcd(Right[i + 1],b[i]);
}
int ans = 1;
for(int i = 1; i < n - 1; i++){
ans = max(ans,gcd(Left[i - 1],Right[i + 1]));
}
ans = max(ans,Right[1]);
ans = max(ans,Left[n - 2]);
printf("%d\n",ans);
}
return 0;
}