Maximize count of distinct elements possible in an Array from the given operation | Function to find the gcd of two numbers ; Function to calculate and return the count of maximum possible distinct elements in the array ; Find the maximum element ; Base Case ; Finding the gcd of first two element ; Calculate Gcd of the array ; Return the total count of distinct elements ; Driver Code
function gcd ( x , y ) { if ( x == 0 ) return y ; return gcd ( y % x , x ) ; } function findDistinct ( arr , n ) { let maximum = Math . max ( ... arr ) ; if ( n == 1 ) return 1 ; if ( n == 2 ) { return ( maximum / gcd ( arr [ 0 ] , arr [ 1 ] ) ) ; } let k = gcd ( arr [ 0 ] , arr [ 1 ] ) ; for ( let i = 2 ; i < n ; i ++ ) { k = gcd ( k , arr [ i ] ) ; } return ( maximum / k ) ; } let arr = [ 1 , 2 , 3 , 5 ] ; let n = arr . length ; document . write ( findDistinct ( arr , n ) ) ;