k | Python Program to print kth prime factor ; A function to generate prime factors of a given number n and return k - th prime factor ; Find the number of 2 's that divide k ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , store i and divide n ; This condition is to handle the case where n is a prime number greater than 2 ; Driver Program
import math NEW_LINE def kPrimeFactor ( n , k ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT k = k - 1 NEW_LINE n = n / 2 NEW_LINE if ( k == 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT i = 3 NEW_LINE while i <= math . sqrt ( n ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT return i NEW_LINE DEDENT k = k - 1 NEW_LINE n = n / i NEW_LINE DEDENT i = i + 2 NEW_LINE DEDENT if ( n > 2 and k == 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return - 1 NEW_LINE DEDENT n = 12 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k ) ) NEW_LINE n = 14 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k ) ) NEW_LINE