Problem: Kth Prime factor of a Number

  • Difficulty: Easy

Given two numbers n and k, print Kth prime factor among all prime factors of n.

Note: if k > all the count of prime factor of n, then print -1

Input:

The first line of input contains an integer denoting the no of test cases. Then T test cases follow. Each test case contains two space seperated integers n and k respectively.
Output:

For each test case ouput a simple line containing a single integer denoting kth prime factor of n.
Constraints:

1<=T<=100
0<=N<=104
1<=K<=50
Example:

Input:

2
225 2
81 5

Ouput:

3
-1

Explanation:

Test Case 1:  n=225 and k=2

Prime factor of 225 are: 3,3,5,5

Kth prime factor is 3

Test Case 2: n=81 and k=5

Prime factor of 81 is 3,3,3,3

since k is greater than all the count of prime factor, hence we print -1

Approach: This is not the fastest solution, but it’s fairly fast. Enough to paste the biggest test case in less than 100 ms. Using sieve of Eratosthenes to generate first 10000 primes, then use it as a dictionary to find all prime factors of a number. There are multiple ways to solve this problem, since the constraints is not big, so this solution is not only simple but fast.

Implementation: Python 2.7

#code
import math
def sieveOfEratosthenes(n):
    sieve = [True]*(n+1)
    sieve[0] = sieve[1] = False
    for i in range(2, int(math.sqrt(n))):
        if sieve[i]:
            for j in range(i+i, len(sieve), i):
                sieve[j] = False
    return [i for i in range(len(sieve)) if sieve[i]]

def primeFactors(number, primes):
    factors, i = [], 0
    while number > 1:
        if number % primes[i] == 0:
            factors.append(primes[i])
            number /= primes[i]
        else:
            i += 1
    return factors

def main():
    t = input()
    primes = sieveOfEratosthenes(10000)
    for _ in range(t):
        number, k = map(int, raw_input().strip().split())
        factors = primeFactors(number, primes)
        print -1 if k > len(factors) else factors[k-1]
        
if __name__ == '__main__':
    main()
Advertisements