Data Structure
 Networking
 RDBMS
 Operating System
 Java
 MS Excel
 iOS
 HTML
 CSS
 Android
 Python
 C Programming
 C++
 C#
 MongoDB
 MySQL
 Javascript
 PHP
- Selected Reading
 - UPSC IAS Exams Notes
 - Developer's Best Practices
 - Questions and Answers
 - Effective Resume Writing
 - HR Interview Questions
 - Computer Glossary
 - Who is Who
 
Find an array element such that all elements are divisible by it using c++
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
#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
Advertisements