51Nod-1179 最大的最大公约数(有技巧的暴力)

给出N个正整数,找出N个数两两之间最大公约数的最大值。例如:N = 4,4个数为:9 15 25 16,两两之间最大公约数的最大值是15同25的最大公约数5。

Input

第1行:一个数N,表示输入正整数的数量。(2 <= N <= 50000)
第2 - N + 1行:每行1个数,对应输入的正整数.(1 <= S[i] <= 1000000)

Output

输出两两之间最大公约数的最大值。

Input示例

4
9
15
25
16

Output示例

5

PS:这个题如果用O(n^2)的做法,肯定会超时的,所以这里有种有技巧的暴力(看大佬博客懂得)。他说要选取最大公约数,我们就从最大的一个数遍历,然后每次加一个数,如果能够加到数列中有的两个数的话,就说明这两个数的最大公约数是加的这个数。

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=1e6+10;
const int mod=1e9+7;
const int inf=1e8;
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
int a[maxn];
int main()
{
    int n,l=0;
    cin>>n;
    me(a,0);
    for(int i=0;i<n;i++)
    {
        int x;scanf("%d",&x);
        a[x]++;
        l=max(l,x);
    }
    for(int i=l;l>=1;i--)
    {
        int s=0;
        for(int j=i;j<=l;j+=i)
        {
            s+=a[j];
            if(s>=2)
            {
                cout<<i<<endl;
                return 0;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41292370/article/details/82501136
今日推荐