LCM of unique elements present in an array | Java program for the above approach ; 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
import java . util . HashMap ; import java . util . Map . Entry ; class GFG { static int findGCD ( int a , int b ) { if ( b == 0 ) return a ; return findGCD ( b , a % b ) ; } static int findLCM ( int a , int b ) { return ( a * b ) / findGCD ( a , b ) ; } static void uniqueElementsLCM ( int arr [ ] , int N ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { freq . put ( arr [ i ] , freq . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; } int lcm = 1 ; for ( Entry < Integer , Integer > i : freq . entrySet ( ) ) { if ( i . getValue ( ) == 1 ) { lcm = findLCM ( lcm , i . getKey ( ) ) ; } } if ( lcm == 1 ) lcm = - 1 ; System . out . print ( lcm ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 3 , 3 , 4 } ; int N = arr . length ; uniqueElementsLCM ( arr , N ) ; } }