大意:输入一个数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!
InputThe 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.
OutputPrint 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.
Examples3 2 2 4
2
5 2 1 3 1 6
1
3 2 3 5
-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;
}