k | python3 program to find k - th prime factor using Sieve Of Eratosthenes . This program is efficient when we have a range of numbers . ; Using SieveOfEratosthenes to find smallest prime factor of all the numbers . For example , if MAX is 10 , s [ 2 ] = s [ 4 ] = s [ 6 ] = s [ 10 ] = 2 s [ 3 ] = s [ 9 ] = 3 s [ 5 ] = 5 s [ 7 ] = 7 ; Create a boolean array " prime [ 0 . . MAX ] " and initialize all entries in it as false . ; Initializing smallest factor equal to 2 for all the even numbers ; For odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number " i * j " . ; Function to generate prime factors and return its k - th prime factor . s [ i ] stores least prime factor of i . ; Keep dividing n by least prime factor while either n is not 1 or count of prime factors is not k . ; To keep track of count of prime factors ; Divide n to find next prime factor ; s [ i ] is going to store prime factor of i .
MAX = 10001 NEW_LINE def sieveOfEratosthenes ( s ) : NEW_LINE INDENT prime = [ False for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( 2 , MAX + 1 , 2 ) : NEW_LINE INDENT s [ i ] = 2 ; NEW_LINE DEDENT for i in range ( 3 , MAX , 2 ) : NEW_LINE INDENT if ( prime [ i ] == False ) : NEW_LINE INDENT s [ i ] = i NEW_LINE for j in range ( i , MAX + 1 , 2 ) : NEW_LINE INDENT if j * j > MAX : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ i * j ] == False ) : NEW_LINE INDENT prime [ i * j ] = True NEW_LINE s [ i * j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def kPrimeFactor ( n , k , s ) : NEW_LINE INDENT while ( n > 1 ) : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT return s [ n ] NEW_LINE DEDENT k -= 1 NEW_LINE n //= s [ n ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT s = [ - 1 for i in range ( MAX + 1 ) ] NEW_LINE sieveOfEratosthenes ( s ) NEW_LINE n = 12 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k , s ) ) NEW_LINE n = 14 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k , s ) ) NEW_LINE