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

C++Server Side ProgrammingProgramming

In this problem, we are given two integer values N and k. Our task is to find the k-th smallest divisor of a natural number N.

Let's take an example to understand the problem,

Input : N = 15, k = 3
Output : 5

Explanation

Factors of 15 are 1, 3, 5, 15
3rd smallest is 5

Solution Approach

A simple solution to the problem is by finding the factors of the number and storing them in sorted manner and printing kth values.

For sorting, we will loop till root(N) and check if N is divisible by i. And store the value of i and (N/i) in an array and sort it. From this sorted array, print k-th value.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
void findFactorK(int n, int k){
   int factors[n/2];
   int j = 0;
   for (int i = 1; i <= sqrt(n); i++) {
      if (n % i == 0) {
         factors[j] = i;
         j++;
         if (i != sqrt(n)){
            factors[j] = n/i;
            j++;
         }
      }
   }
   sort(factors, factors + j);
   if (k > j)
      cout<<"Doesn't Exist";
   else
      cout<<factors[k-1];
}
int main(){
   int N = 16,
   k = 3;
   cout<<k<<"-th smallest divisor of the number "<<N<<" is ";
   findFactorK(N, k);
   return 0;
}

Output

3-th smallest divisor of the number 16 is 4

Another approach

Another approach to solve the problem is using two arrays which are sorted.

One storing values i, sorted in ascending order.

Other storing values N/i, sorted in descending order.

We will find the kth smallest value form either of the two arrays. If k is greater than the size of the array, it is present in the second array from last.

Otherwise it is present in the first array.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
void findFactorK(int n, int k){
   int factors1[n/2];
   int factors2[n/2];
   int f1 = 0,f2 = 0;
   for (int i = 1; i <= sqrt(n); i++) {
      if (n % i == 0) {
         factors1[f1] = i;
         f1++;
         if (i != sqrt(n)){
            factors2[f2] = n/i;
            f2++;
         }
      }
   }
   if (k > (f1 + f2))
      cout<<"Doesn't Exist";
   else{
      if(k <= f1)
         cout<<factors1[f1-1];
      else
         cout<<factors2[k - f2 - 1];
   }
}
int main(){
   int N = 16,
   k = 3;
   cout<<k<<"-th smallest divisor of the number "<<N<<" is ";
   findFactorK(N, k);
   return 0;
}

Output

3-th smallest divisor of the number 16 is 4
raja
Updated on 28-Jan-2022 08:20:50

Advertisements