Find element in array that divides all array elements | 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
function gcd ( a , b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } function findNumber ( arr , n ) { let ans = arr [ 0 ] ; for ( let i = 0 ; i < n ; i ++ ) ans = gcd ( ans , arr [ i ] ) ; for ( let i = 0 ; i < n ; i ++ ) if ( arr [ i ] == ans ) return ans ; return - 1 ; } let arr = [ 2 , 2 , 4 ] ; let n = arr . length ; document . write ( findNumber ( arr , n ) ) ;