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 vector ; 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
< ? php function kFactors ( $ n , $ k ) { $ P = array ( ) ; while ( $ n % 2 == 0 ) { array_push ( $ P , 2 ) ; $ n = ( int ) ( $ n / 2 ) ; } for ( $ i = 3 ; $ i * $ i <= $ n ; $ i = $ i + 2 ) { while ( $ n % $ i == 0 ) { $ n = ( int ) ( $ n / $ i ) ; array_push ( $ P , $ i ) ; } } if ( $ n > 2 ) array_push ( $ P , $ n ) ; if ( count ( $ P ) < $ k ) { echo " - 1 STRNEWLINE " ; return ; } for ( $ i = 0 ; $ i < $ k - 1 ; $ i ++ ) echo $ P [ $ i ] . " , " $ product = 1 ; for ( $ i = $ k - 1 ; $ i < count ( $ P ) ; $ i ++ ) $ product = $ product * $ P [ $ i ] ; echo $ product ; } $ n = 54 ; $ k = 3 ; kFactors ( $ n , $ k ) ; ? >