LCM of unique elements present in an array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findGCD ( int a , int b ) { if ( b == 0 ) return a ; return findGCD ( b , a % b ) ; } int findLCM ( int a , int b ) { return ( a * b ) / findGCD ( a , b ) ; } int uniqueElementsLCM ( int arr [ ] , int N ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] ] ++ ; } int lcm = 1 ; for ( auto i : freq ) { if ( i . second == 1 ) { lcm = findLCM ( lcm , i . first ) ; } } if ( lcm == 1 ) lcm = -1 ; cout << lcm ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 3 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; uniqueElementsLCM ( arr , N ) ; return 0 ; }