Find the k-th smallest divisor of a natural number N

You’re given a number N and a number K. Our task is to find the kth smallest divisor of N.

Examples:

Input : N = 12, K = 5
Output : 6
The divisors of 12 after sorting are 1, 2, 3, 4, 6 and 12. 
Where the value of 5th divisor is equal to 6.

Input : N = 16, K 2
Output : 2

Simple Approach: A simple approach is to run a loop from 1 to √N and find all factors of N and push them into a vector. Finally, sort the vector and print the K-th value from the vector.

Note: Elements in the vector will not be sorted initially as we are pushing both factors (i) and (n/i). That is why it is needed to sort the vector before printing the K-th factor.

Below is the implementation of above approach :

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find K-th smallest factor
  
#include <bits/stdc++.h>
using namespace std;
  
// function to find the k'th divisor
void findkth(int n, int k)
{
    // initialize a vector v
    vector<long long> v;
  
    // store all the divisors
    // so the loop will needs to run till sqrt ( n )
    for (int i = 1; i <= sqrt(n); i++) {
        if (n % i == 0) {
            v.push_back(i);
            if (i != sqrt(n))
                v.push_back(n / i);
        }
    }
  
    // sort the vector in an increasing order
    sort(v.begin(), v.end());
  
    // if k is greater than the size of vector
    // then no divisor can be possible
    if (k > v.size())
        cout << "Doesn't Exist";
    // else print the ( k - 1 )th value of vector
    else
        cout << v[k - 1];
}
  
// Driver code
int main()
{
    int n = 15, k = 2;
  
    findkth(n, k);
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find K-th smallest factor
from math import sqrt
  
# function to find the k'th divisor
def findkth(n, k):
      
    # initialize a vector v
    v = []
  
    # store all the divisors so the loop 
    # will needs to run till sqrt ( n )
    p = int(sqrt(n)) + 1
    for i in range(1, p, 1):
        if (n % i == 0):
            v.append(i)
            if (i != sqrt(n)):
                v.append(n / i);
          
    # sort the vector in an increasing order
    v.sort(reverse = False)
  
    # if k is greater than the size of vector
    # then no divisor can be possible
    if (k > len(v)):
        print("Doesn't Exist")
          
    # else print the (k - 1)th 
    # value of vector
    else:
        print(v[k - 1])
  
# Driver code
if __name__ == '__main__':
    n = 15
    k = 2
  
    findkth(n, k)
  
# This code is contributed by
# Surendra_Gangwar

chevron_right