Find element in array that divides all array elements | JAVA program to find such number in the array that all array elements are divisible by it ; Returns GCD of two numbers ; Function to return the desired number if exists ; Find GCD of array ; Check if GCD is present in array ; Driver Code
import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int findNumber ( int arr [ ] , int n ) { int ans = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) ans = gcd ( ans , arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == ans ) return ans ; return - 1 ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 2 , 4 } ; int n = arr . length ; System . out . println ( findNumber ( arr , n ) ) ; } }