- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find the kth factor of n using Python

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

- Related Questions & Answers
- Program to find Kth bit in n-th binary string using Python
- Program to find kth lexicographic sequence from 1 to n of size k Python
- Program to find kth smallest n length lexicographically smallest string in python
- Print the kth common factor of two numbers
- Golang Program to toggle the Kth of the given number n.
- Program to find Kth ancestor of a tree node in Python
- Python program to find the character position of Kth word from a list of strings
- Program to find the kth missing number from a list of elements in Python
- Program to find largest kth index value of one list in Python
- Python Program for Find largest prime factor of a number
- Program to find highest common factor of a list of elements in Python
- Program to find kth smallest element in linear time in Python
- Python – Find Kth Even Element
- C++ Program to find kth Smallest Element by the Method of Partitioning the Array
- Program to find the kth smallest element in a Binary Search Tree in Python