LCM of unique elements present in an array | Function to find GCD of two numbers ; Base Case ; Recursively find the GCD ; Function to find LCM of two numbers ; Function to find LCM of unique elements present in the array ; Stores the frequency of each number of the array ; Store the frequency of each element of the array ; Store the required result ; Traverse the map freq ; If the frequency of the current element is 1 , then update ans ; If there is no unique element , set lcm to - 1 ; Print the result ; Driver Code ; Function Call
function findGCD ( a , b ) { if ( b == 0 ) return a ; return findGCD ( b , a % b ) ; } function findLCM ( a , b ) { return ( a * b ) / findGCD ( a , b ) ; } function uniqueElementsLCM ( arr , N ) { var freq = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { if ( freq . has ( arr [ i ] ) ) { freq . set ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . set ( arr [ i ] , 1 ) ; } } var lcm = 1 ; freq . forEach ( ( value , key ) => { if ( value == 1 ) { lcm = findLCM ( lcm , key ) ; } } ) ; if ( lcm == 1 ) lcm = - 1 ; document . write ( lcm ) ; } var arr = [ 1 , 2 , 1 , 3 , 3 , 4 ] ; var N = arr . length ; uniqueElementsLCM ( arr , N ) ;