找出一个数组里能把所有数整除的那个数(包含vector的简单应用)

大意:输入一个数n,代表这个数组有n个数,找出能把数组中所有数整除的那个数,若果没有则输出-1。

Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.

Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!

Input

The first line contains integer n (1 ≤ n ≤ 105), showing how many numbers the array has. The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the array elements.

Output

Print a single integer — the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1.

If there are multiple answers, you are allowed to print any of them.

Examples
Input
3
2 2 4
Output
2
Input
5
2 1 3 1 6
Output
1
Input
3
2 3 5
Output
-1

错因;知道符合要求的这个数一定比被除数小,否则不可能整除,比如2%3不可能等于0,即不可能整除。但是就是没想到既然这个数比所有数都要小,那一定就是整个数组里最小的数啊!!!!从小到大排序后就是***a[0]***,所以只需要判断a[0]能不能把所有数整除即可,不需要把每个数都判断一下,如果把所有数都判断一下能不能被所有数整除,即使只要发现不能被整除的数就跳出循环,可还要对每个数都做出这样能否被所有数整除的判断,时间一定是超限的!!!

两种代码(方法一样,只是第二个是用vector进行对数据的输入的,排序也是用的sort(a.begin(),a.end()而已)

普通:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n,i;
    cin>>n;
    int a[n];
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    sort(a,a+n);
    for(i=0;i<n;i++)
    {
        if(a[i]%a[0]!=0)
        {
            cout<<"-1";
            break;
        }
        if(i==n-1)
        cout<<a[0];
    }
    return 0;
}

用vector;

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n,i,k;
    vector <int> a;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>k;
        a.push_back(k);
    }
    sort(a.begin(),a.end());
    for(i=0;i<n;i++)
    {
         if(a[i]%a[0]!=0)
        {
            cout<<"-1";
            break;
        }
        if(i==n-1)
        cout<<a[0];
    }
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值