text: k | 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 code
code: function kPrimeFactor ( n , k ) { while ( n % 2 == 0 ) { k -- ; n = n / 2 ; if ( k == 0 ) return 2 ; } for ( let i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { if ( k == 1 ) return i ; k -- ; n = n / i ; } } if ( n > 2 && k == 1 ) return n ; return - 1 ; } let n = 12 , k = 3 ; document . write ( kPrimeFactor ( n , k ) + " " ) ; n = 14 ; k = 3 ; document . write ( kPrimeFactor ( n , k ) ) ;