LCM of unique elements present in an array | Python3 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
from collections import defaultdict NEW_LINE def findGCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return findGCD ( b , a % b ) NEW_LINE DEDENT def findLCM ( a , b ) : NEW_LINE INDENT return ( a * b ) // findGCD ( a , b ) NEW_LINE DEDENT def uniqueElementsLCM ( arr , N ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT lcm = 1 NEW_LINE for i in freq : NEW_LINE INDENT if ( freq [ i ] == 1 ) : NEW_LINE INDENT lcm = findLCM ( lcm , i ) NEW_LINE DEDENT DEDENT if ( lcm == 1 ) : NEW_LINE INDENT lcm = - 1 NEW_LINE DEDENT print ( lcm ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 3 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE uniqueElementsLCM ( arr , N ) NEW_LINE DEDENT