Construct longest possible sequence of unique elements with given LCM | Java program to implement the above approach ; Function to construct an array of unique elements whose LCM is N ; Stores array elements whose LCM is N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If N is divisible by i ; Insert i into newArr [ ] ; If N is not perfect square ; Sort the array newArr [ ] ; Print array elements ; Driver Code ; Given N ; Function Call
import java . util . Arrays ; class GFG { static void constructArrayWithGivenLCM ( int N ) { int newArr [ ] = new int [ N ] ; int j = 0 ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { newArr [ j ] = i ; j ++ ; if ( N / i != i ) { newArr [ j ] = N / i ; j ++ ; } } } Arrays . sort ( newArr ) ; for ( int i = j ; i < N ; i ++ ) { System . out . print ( newArr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 12 ; constructArrayWithGivenLCM ( N ) ; } }