Find if n can be written as product of k numbers | Prints k factors of n if n can be written as multiple of k numbers . Else prints - 1. ; A vector to store all prime factors of n ; Insert all 2 's in list ; n must be odd at this point So we skip one element ( i = i + 2 ) ; This is to handle when n > 2 and n is prime ; If size ( P ) < k , k factors are not possible ; printing first k - 1 factors ; calculating and printing product of rest of numbers ; Driver code
function kFactors ( n , k ) { var P = Array ( ) ; while ( n % 2 == 0 ) { P . push ( 2 ) ; n = parseInt ( n / 2 ) ; } for ( i = 3 ; i * i <= n ; i = i + 2 ) { while ( n % i == 0 ) { n = parseInt ( n / i ) ; P . push ( i ) ; } } if ( n > 2 ) P . push ( n ) ; if ( P . length < k ) { document . write ( " " ) ; return ; } for ( i = 0 ; i < k - 1 ; i ++ ) document . write ( P [ i ] + " " ) ; var product = 1 ; for ( i = k - 1 ; i < P . length ; i ++ ) product = product * P [ i ] ; document . write ( product ) ; } var n = 54 , k = 3 ; kFactors ( n , k ) ;