Find an array element such that all elements are divisible by it

14 Jun, 2022
Given an array of numbers, find the number among them such that all numbers are divisible by it. If not possible print -1.Examples:  
Input : arr = {25, 20, 5, 10, 100} 
Output : 5 
Explanation : 5 is an array element
 which divides all numbers.

Input : arr = {9, 3, 6, 2, 15} 
Output : -1 
Explanation : No numbers are divisible
by any array element.
 
Method 1:(naive) A normal approach will be to take every element and check for division with all other elements. If all the numbers are divisible then return the number.  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find an array element that// divides all numbers in the array using// naive approach#include <bits/stdc++.h>using namespace std; // function to find smallest numint findSmallest(int a[], int n){    // traverse for all elements    for (int i = 0; i < n; i++) {                 int j;        for (j = 0; j < n; j++)            if (a[j] % a[i])                break;         // stores the minimum if        // it divides all        if (j == n)            return a[i];    }     return -1;} // driver codeint main(){    int a[] = { 25, 20, 5, 10, 100 };    int n = sizeof(a) / sizeof(int);    cout << findSmallest(a, n);    return 0;}
// Java program to find an array element// that divides all numbers in the array// using naive approachimport java.io.*; class GFG {         // function to find smallest num    static int findSmallest(int a[], int n)    {        // traverse for all elements        for (int i = 0; i < n; i++)        {                         int j;            for (j = 0; j < n; j++)                if (a[j] % a[i]>=1)                    break;                 // stores the minimum if            // it divides all            if (j == n)                return a[i];        }             return -1;    }         // driver code    public static void main(String args[])    {        int a[] = { 25, 20, 5, 10, 100 };        int n = a.length;        System.out.println(findSmallest(a, n));    }}  // This code is contributed by Nikita Tiwari.
# Python 3 program to find an array# element that divides all numbers# in the array using naive approach # Function to find smallest numdef findSmallest(a, n) :         # Traverse for all elements    for i in range(0, n ) :                 for j in range(0, n) :                         if ((a[j] % a[i]) >= 1) :                break         # Stores the minimum        # if it divides all        if (j == n - 1) :            return a[i]                     return -1  # Driver codea = [ 25, 20, 5, 10, 100 ]n = len(a)print(findSmallest(a, n))  # This code is contributed by Nikita Tiwari.
// C# program to find an array element// that divides all numbers in the array// using naive approachusing System; class GFG {         // function to find smallest num    static int findSmallest(int []a, int n)    {        // traverse for all elements        for (int i = 0; i < n; i++)        {                         int j;            for (j = 0; j < n; j++)                if (a[j] % a[i] >= 1)                    break;                 // stores the minimum if            // it divides all            if (j == n)                return a[i];        }             return -1;    }         // Driver code    public static void Main()    {        int []a = { 25, 20, 5, 10, 100 };        int n = a.Length;        Console.WriteLine(findSmallest(a, n));    }}  // This code is contributed by vt_m.
<?php// PHP program to find an array// element that divides all// numbers in the array using// naive approach // function to find smallest numfunction findSmallest($a, $n){         // traverse for all elements    for ($i = 0; $i < $n; $i++)    {        $j;        for ($j = 0; $j < $n; $j++)            if ($a[$j] % $a[$i])                break;         // stores the minimum if        // it divides all        if ($j == $n)            return $a[$i];    }     return -1;}     // Driver Code    $a = array( 25, 20, 5, 10, 100 );    $n = sizeof($a);    echo findSmallest($a, $n); // This code is contributed by nitin mittal?>
<script> // JavaScript program to find an array element// that divides all numbers in the array// using naive approach     // function to find smallest num    function findSmallest(a, n)    {        // traverse for all elements        for (let i = 0; i < n; i++)        {                           let j;            for (j = 0; j < n; j++)                if (a[j] % a[i]>=1)                    break;                   // stores the minimum if            // it divides all            if (j == n)                return a[i];        }               return -1;    }  // Driver code         let a = [ 25, 20, 5, 10, 100 ];        let n = a.length;        document.write(findSmallest(a, n)); </script>
Output : 
5
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2 : (Efficient) An efficient approach is to find smallest of all numbers, and check if it divides all the other numbers, if yes then the smallest number will be the required number.  
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the smallest number// that divides all numbers in an array#include <bits/stdc++.h>using namespace std; // function to find smallest numint findSmallest(int a[], int n){    // Find the smallest element    int smallest = *min_element(a, a+n);         // Check if all array elements    // are divisible by smallest.    for (int i = 1; i < n; i++)            if (a[i] % smallest)            return -1;     return smallest;} // Driver codeint main(){    int a[] = { 25, 20, 5, 10, 100 };    int n = sizeof(a) / sizeof(int);       cout << findSmallest(a, n);       return 0;}
// Java Program to find the// smallest number that divides// all numbers in an arrayimport java.io.*; class GFG {     // function to find the smallest element    static int min_element(int a[])    {        int min = Integer.MAX_VALUE, i;        for (i = 0; i < a.length; i++)        {            if (a[i] < min)                min = a[i];        }                 return min;    }         // function to find smallest num    static int findSmallest(int a[], int n)    {        // Find the smallest element        int smallest = min_element(a);             // Check if all array elements        // are divisible by smallest.        for (int i = 1; i < n; i++)        if (a[i] % smallest >= 1)            return -1;             return smallest;    }         // Driver code    public static void main(String args[])    {        int a[] = {25, 20, 5, 10, 100};        int n = a.length;        System.out.println(findSmallest(a, n));    }} // This code is contributed by Nikita Tiwari.
# Python3 Program to find the# smallest number that divides# all numbers in an array # Function to find the smallest elementdef min_element(a) :         m = 10000000         for i in range(0, len(a)) :                 if (a[i] < m) :            m = a[i]         return m # Function to find smallest numdef findSmallest(a, n) :         # Find the smallest element    smallest = min_element(a)         # Check if all array elements    # are divisible by smallest.    for i in range(1, n) :                 if (a[i] % smallest >= 1) :            return -1     return smallest  # Driver code a = [ 25, 20, 5, 10, 100 ]n = len(a)print(findSmallest(a, n))  # This code is contributed by Nikita Tiwari.
// C# Program to find the// smallest number that divides// all numbers in an arrayusing System; class GFG {     // function to find the smallest element    static int min_element(int []a)    {        int min = int.MaxValue;        int i;        for (i = 0; i < a.Length; i++)        {            if (a[i] < min)                min = a[i];        }                 return min;    }         // function to find smallest num    static int findSmallest(int []a, int n)    {        // Find the smallest element        int smallest = min_element(a);             // Check if all array elements        // are divisible by smallest.        for (int i = 1; i < n; i++)        if (a[i] % smallest >= 1)            return -1;             return smallest;    }         // Driver code    public static void Main()    {        int []a = {25, 20, 5, 10, 100};        int n = a.Length;        Console.WriteLine(findSmallest(a, n));    }} // This code is contributed by vt_m.
<?php// PHP Program to find the smallest number// that divides all numbers in an array // function to find smallest numfunction findSmallest($a, $n){         // Find the smallest element    $smallest = min($a);         // Check if all array elements    // are divisible by smallest.    for ($i = 1; $i < $n; $i++)        if ($a[$i] % $smallest)            return -1;     return $smallest;}     // Driver Code    $a = array(25, 20, 5, 10, 100);    $n =count($a);    echo findSmallest($a, $n); // This code is contributed by anuj_67.?>
<script>    // Javascript Program to find the    // smallest number that divides    // all numbers in an array         // function to find the smallest element    function min_element(a)    {        let min = Number.MAX_VALUE;        let i;        for (i = 0; i < a.length; i++)        {            if (a[i] < min)                min = a[i];        }                  return min;    }          // function to find smallest num    function findSmallest(a, n)    {        // Find the smallest element        let smallest = min_element(a);              // Check if all array elements        // are divisible by smallest.        for (let i = 1; i < n; i++)        if (a[i] % smallest >= 1)            return -1;              return smallest;    }         let a = [25, 20, 5, 10, 100];    let n = a.length;    document.write(findSmallest(a, n));         // This code is contributed by divyeshrabadiya07.</script>
Output :  
5
Time Complexity: O(n) 
Auxiliary Space: O(1) 
Find an array element such that all elements are divisible by it | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersFind an array element such that all elements are divisible by it | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=RglGlzkliNM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p 
nitin mittal
vt_m
sanjoy_62
divyeshrabadiya07
_shinchancode
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Find Second largest element in an array
Introduction to Data Structures
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Binary Search
Search an element in a sorted and rotated array
Search, insert and delete in an unsorted array
Find the Missing Number
Median of two sorted arrays of different sizes