B - Coprime Sequence

Description

Do you know what is called ``Coprime Sequence''? That is a sequence consists of $n$ 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.
 

Input

The first line of the input contains an integer $T(1\leq T\leq10)$, denoting the number of test cases.
In each test case, there is an integer $n(3\leq n\leq 100000)$ in the first line, denoting the number of integers in the sequence.
Then the following line consists of $n$ integers $a_1,a_2,...,a_n(1\leq a_i\leq 10^9)$, 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

 


题意:去掉任意一个数 求剩下的那些数的最大公约数
代码:
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[100005],pre[100005],nex[100005];
int GCD(int x,int y)
{
   if(x==0)
        return y;
    else
        return GCD(y%x,x);
}
int main()
{
    int t,n,ans,i,j,k,d;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        pre[1]=a[1];              //前一个数的最大公约数
        nex[n]=a[n];             //后一个数的最大公约数
        for(i=2;i<=n;i++)
            pre[i]=GCD(a[i],pre[i-1]);         //前i个数的最大公约数
        for(i=n-1;i>=1;i--)
            nex[i]=GCD(a[i],nex[i+1]);        //后i个数的最大公约数 
        ans=max(pre[n-1],nex[2]);           //去掉第一个或最后一个时的最大公约数
        for(i=2;i<=n;i++)
            ans=max(ans,GCD(pre[i-1],nex[i+1]));         //去掉第i个时的最大公约数
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41700151/article/details/80302123