Find if n can be written as product of k numbers | Python3 program to find if it is possible to write a number n as product of exactly k positive numbers greater than 1. ; Prints k factors of n if n can be written as multiple of k numbers . Else prints - 1 ; list 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 ( a ) < k , k factors are not possible ; printing first k - 1 factors ; calculating and printing product of rest of numbers ; Driver code
import math as mt NEW_LINE def kFactors ( n , k ) : NEW_LINE INDENT a = list ( ) NEW_LINE while n % 2 == 0 : NEW_LINE INDENT a . append ( 2 ) NEW_LINE n = n // 2 NEW_LINE DEDENT for i in range ( 3 , mt . ceil ( mt . sqrt ( n ) ) , 2 ) : NEW_LINE INDENT while n % i == 0 : NEW_LINE INDENT n = n / i ; NEW_LINE a . append ( i ) NEW_LINE DEDENT DEDENT if n > 2 : NEW_LINE INDENT a . append ( n ) NEW_LINE DEDENT if len ( a ) < k : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( k - 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " , ▁ " ) NEW_LINE DEDENT product = 1 NEW_LINE for i in range ( k - 1 , len ( a ) ) : NEW_LINE INDENT product *= a [ i ] NEW_LINE DEDENT print ( product ) NEW_LINE DEDENT n , k = 54 , 3 NEW_LINE kFactors ( n , k ) NEW_LINE