C - Coprime Sequence

C - Coprime Sequence

 

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.
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个数最大公约数为1。如果删掉一个数,使剩下的数的最大公约数最大,求这个集合的最大公约数。

方法一:

思路:

设这个最大公约数为x。

n个数先排序 —>  a1,a2,a3......an

那必须有n-1个数都能除以x,即n-1个数都>=x

所以x最大是a2(排第二的数,不一定是第二小的)

所以,x的取值  i=a2;i>=1;i--  ,依次用ai除,当有n-1个数都可以除时,这个i为x


代码:

#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
    int t;
    cin>>t;
    int n;
    int a[100005];
    while(t--)
    {
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
        }
        sort(a,a+n);
        int h=a[1];
        int flag=0;
        for(int j=h;j>=1;j--)
        {
            int sum=0;
            for(int i=0;i<n;i++)
            {
                if(a[i]%j==0)
                    sum++;
                if(sum>=n-1)
                {
                    flag=1;
                    cout<<j<<endl;
                    break;
                }
            }
            if(flag==1)
                break;
        }
    }
    return 0;
}

方法二:

思路:

题意:给你一个序列,任意去掉一个,问整个序列的最大公约数。 
前缀和,后缀和思想 
求前缀最大公约数,后缀最大公约数,然后找gcd(前缀gcd,后缀gcd)中最大的。 
具体思想:开两个数组,第一个数组a保存前缀gcd,a[i]表示,从1到i的最大公约数。第二个数组b保存后缀gcd,b[i]表示,从n到i的最大公约数。 
去掉第i个数的最大公约数为gcd(a[i-1],b[i+1]).over!

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod = 1e9 + 7;
const ll maxn = 100005;
int l[maxn],r[maxn],num[maxn];
int main(){
    std::ios::sync_with_stdio(false);
    int T;cin>>T;
    while(T--){
        int n;cin>>n;
        for(int i=0;i<n;i++) cin>>num[i];
        l[0] = num[0];
        r[n-1] = num[n-1];
        for(int i=1;i<n;i++)
            l[i] = __gcd(l[i-1],num[i]);
        for(int i=n-2;i>=0;i--)
            r[i] = __gcd(r[i+1],num[i]);
        int d = max(l[n-2],r[1]);
        for(int i=1;i<n-1;i++){
            d = max(d,__gcd(l[i-1],r[i+1]));
        }
        cout<<d<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值