Suppose we have two positive values n and k. Now consider we have a list of all factors of n sorted in ascending order, we have to find the kth factor in this list. If there are less than k factors, then return -1.
So, if the input is like n = 28 k = 4, then the output will be 7 because, the factors of 28 are [1,2,4,7,14,28], fourth one is 7.
To solve this, we will follow these steps −
if k is same as 1, then
cand := a list with one element 
for i in range 2 to 1 + floor of(square root of n), do
if n mod i is same as 0, then
insert i at the end of cand
m := size of cand
if k > 2*m or (k is same as 2*m and n = (last element of cand)^2)
if k <= m, then
factor := cand[2*m - k]
return quotient of n/factor
Let us see the following implementation to get better understanding −
from math import floor def solve(n ,k): if k == 1: return 1 cand =  for i in range(2, 1+floor(pow(n, 0.5))): if n%i == 0: cand.append(i) m = len(cand) if k > 2*m or (k == 2*m and n == cand[-1]**2): return -1 if k <= m: return cand[k-1] factor = cand[2*m - k] return n//factor n = 28 k = 4 print(solve(n ,k))