Minimum LCM of all pairs in a given array | function that return pair having minimum LCM ; Find max element in the array as the gcd of two elements from the array can 't greater than max element. ; Created a 2D array to store minimum two multiple of any particular i . ; We already found two smallest multiple ; Iterating over all gcd ; Iterating over its multiple ; If we already found the two smallest multiple of i ; Choosing smallest two multiple ; Calculating lcm ; Return final answer ; Driver code
function minLCM ( arr , n ) { var mx = 0 ; for ( var i = 0 ; i < n ; i ++ ) { mx = Math . max ( mx , arr [ i ] ) ; } var mul = Array . from ( Array ( mx + 1 ) , ( ) => Array ( ) ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( mul [ arr [ i ] ] . length > 1 ) { continue ; } mul [ arr [ i ] ] . push ( arr [ i ] ) ; } for ( var i = 1 ; i <= mx ; i ++ ) { for ( var j = i + i ; j <= mx ; j += i ) { if ( mul [ i ] . length > 1 ) { break ; } mul [ j ] . forEach ( k => { if ( mul [ i ] . length <= 1 ) { mul [ i ] . push ( k ) ; } } ) ; } } var ans = 1000000000 ; for ( var i = 1 ; i <= mx ; i ++ ) { if ( mul [ i ] . length <= 1 ) continue ; var a = mul [ i ] [ 0 ] , b = mul [ i ] [ 1 ] ; var lcm = ( a * b ) / i ; ans = Math . min ( ans , lcm ) ; } return ans ; } var arr = [ 2 , 4 , 3 , 6 , 5 ] ; var n = arr . length ; document . write ( minLCM ( arr , n ) + " " ) ;