题目:
Codeforce原题链接
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!
题目大意:在数组里找出一个数,这个数是这个数组所有数的因数,如果存在这个数,就输出它,不存在的话输出"-1"
思路:
如果一个数A是另外一个数B的因数,那么A一定小于B,所以我们要找的数在这个数组内肯定是最小的,我们可以先将数组进行升序排序,然后再进行判断。
AC代码:
#include<iostream>
#include<algorithm>
using namespace std;
long long a[100010];
int main()
{
int n;
int i;
int flage = 1;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a, a + n);//sort函数默认升序排序
for (i = 1; i < n; i++)
{
if (a[i] % a[0] != 0)//判断数组内其他数能不能整除最小的数
{
flage = 0;
break;//如果不能,跳出循环,节省时间
}
}
if (flage)
{
cout << a[0];
}
else
{
cout << -1;
}
return 0;
}