Program to find the kth factor of n using Python

PythonServer Side ProgrammingProgramming

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

    • return 1

  • cand := a list with one element [1]

  • 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)

    • return -1

  • if k <= m, then

    • return cand[k-1]

  • factor := cand[2*m - k]

  • return quotient of n/factor

Let us see the following implementation to get better understanding −

Example

from math import floor
def solve(n ,k):
   if k == 1:
      return 1
   cand = [1]
   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))

Input

28, 4

Output

7
raja
Published on 27-May-2021 15:48:33
Advertisements