

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Elements of an array that are not divisible by any element of another array in C++
- Find elements of an array which are divisible by N using STL in C++
- Count numbers in a range that are divisible by all array elements in C++
- Count elements that are divisible by at-least one element in another array in C++
- Print array elements that are divisible by at-least one other in C++
- Find an element in an array such that elements form a strictly decreasing and increasing sequence in Python
- Print all the combinations of N elements by changing sign such that their sum is divisible by M in C++
- Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N in C++
- Add N digits to A such that it is divisible by B after each addition?
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Possible cuts of a number such that maximum parts are divisible by 3 in C++
- Add N digits to A such that it is divisible by B after each addition in C++?
- Find all pairs (a, b) in an array such that a % b = k in C++
- Product of all the elements in an array divisible by a given number K in C++
- Count the number of elements in an array which are divisible by k in C++
Advertisements