Minimum LCM of all pairs in a given array | Java program to find the pair having minimum LCM ; 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
import java . util . Vector ; class GFG { static int minLCM ( int arr [ ] , int n ) { int mx = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mx = Math . max ( mx , arr [ i ] ) ; } Vector < Integer > [ ] mul = new Vector [ mx + 1 ] ; for ( int i = 0 ; i < mul . length ; i ++ ) mul [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mul [ arr [ i ] ] . size ( ) > 1 ) { continue ; } mul [ arr [ i ] ] . add ( arr [ i ] ) ; } for ( int i = 1 ; i <= mx ; i ++ ) { for ( int j = i + i ; j <= mx ; j += i ) { if ( mul [ i ] . size ( ) > 1 ) { break ; } for ( int k : mul [ j ] ) { if ( mul [ i ] . size ( ) > 1 ) break ; mul [ i ] . add ( k ) ; } } } int ans = Integer . MAX_VALUE ; for ( int i = 1 ; i <= mx ; i ++ ) { if ( mul [ i ] . size ( ) <= 1 ) continue ; int a = mul [ i ] . get ( 0 ) , b = mul [ i ] . get ( 1 ) ; int lcm = ( a * b ) / i ; ans = Math . min ( ans , lcm ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 3 , 6 , 5 } ; int n = arr . length ; System . out . print ( minLCM ( arr , n ) + "NEW_LINE"); } }