# Find an array element such that all elements are divisible by it using c++

C++Server Side ProgrammingProgramming

Consider we have an array A with few elements. We have to find an element from A, such that all elements can be divided by it. Suppose the A is like [15, 21, 69, 33, 3, 72, 81], then the element will be 3, as all numbers can be divisible by 3.

To solve this problem, we will take the smallest number in A, then check whether all numbers can be divided by the smallest number or not, if yes, then return the number, otherwise, return false.

## Example

Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
int getNumber(int a[], int n) {
int minNumber = *min_element(a, a+n);
for (int i = 1; i < n; i++)
if (a[i] % minNumber)
return -1;
return minNumber;
}
int main() {
int a[] = { 15, 21, 69, 33, 3, 72, 81 };
int n = sizeof(a) / sizeof(int);
cout << "The number is: "<< getNumber(a, n);
}

## Output

The number is: 3
Published on 29-Oct-2019 15:52:13