
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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++
- Find an element in an array such that elements form a strictly decreasing and increasing sequence in Python
- Multiply the given number by 2 such that it is divisible by 10
- Print array elements that are divisible by at-least one other 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++
- Print all the combinations of N elements by changing sign such that their sum is divisible by M in C++
- Find an element in array such that sum of left array is equal to sum of right array using 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++
- Python Program to check whether it is possible to make a divisible by 3 number using all digits in an array
- Java Program to check whether it is possible to make a divisible by 3 number using all digits in an array
- Add N digits to A such that it is divisible by B after each addition?

Advertisements