Generate longest possible array with product K such that each array element is divisible by its previous adjacent element | Function to construct longest array with product K such that each element is divisible by its previous element ; Stores the prime factors of K ; Stores the power to which primefactor i is raised ; Sort prime factors in descending order ; Stores the final array ; Multiply the last element by K ; Print the constructed array ; Driver Code
function findLongestArray ( K ) { let primefactors = [ ] ; let K_temp = K ; for ( let i = 2 ; i * i <= K ; i ++ ) { let count = 0 ; while ( K_temp % i == 0 ) { K_temp = Math . floor ( K_temp / i ) ; count ++ ; } if ( count > 0 ) primefactors . push ( [ count , i ] ) ; } if ( K_temp != 1 ) primefactors . push ( [ 1 , K_temp ] ) ; primefactors . sort ( function ( x , y ) { if ( x [ 0 ] != y [ 0 ] ) return y [ 0 ] - x [ 0 ] ; return y [ 1 ] - x [ 1 ] ; } ) ; let n = primefactors [ 0 ] [ 0 ] ; let val = primefactors [ 0 ] [ 1 ] ; let answer = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { answer [ i ] = val ; } answer [ n - 1 ] *= K ; for ( let i = 0 ; i < n ; i ++ ) { answer [ n - 1 ] = Math . floor ( answer [ n - 1 ] / val ) ; } document . write ( " " ) ; for ( let i = 0 ; i < answer . length ; i ++ ) { if ( i == answer . length - 1 ) document . write ( answer [ i ] + " " ) ; else document . write ( answer [ i ] + " " ) ; } } let K = 4 ; findLongestArray ( K ) ;