K-th Smallest Prime Fraction in C++


Suppose we have one sorted list, there is 1 and some prime numbers, now for every p < q in the list, we will consider fraction p/q, then we have to find which is the kth smallest fraction. We have to return an array as answer, so ans[0] will be p and ans[1] will be q.

So if the input is like [1,3,5,7], and k = 2, then the answer will be 1/5, as the fractions are 1/3, 1/5, 1/7, 3/5, 3/7, 5/7, the second smallest is 1/5.

To solve this, we will follow these steps −

  • Define Data, this will take a, b and a/b
  • Define an array ret of size 2
  • n := size of A
  • define one priority queue pq
  • for initialize i := 0, when i < n, update (increase i by 1), do −
    • insert Data(A[0], A[i], 0) into pq
  • while K is non-zero, do −
    • temp = top element of pq
    • delete element from pq
    • if K is same as 0, then −
      • ret[0] := a of temp
      • ret[1] := b of temp
      • return ret
    • if temp.idx + 1 < n, then −
      • idx := idx of temp + 1
      • insert Data(A[idx], temp.b, idx) into pq
    • decrease K by 1
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
struct Data{
   double val, a, b;
   int idx;
   Data(double a, double b, int c){
      val = a / b;
      this->a = a;
      this->b = b;
      idx = c;
   }
};
struct Comparator{
   bool operator()(Data a, Data b){
      return !(a.val < b.val);
   }
};
class Solution {
public:
   vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {
      vector <int> ret(2);
      int n = A.size();
      priority_queue <Data, vector <Data>, Comparator> pq;
      for(int i = 0; i < n; i++){
         pq.push(Data(double(A[0]), double(A[i]), 0));
      }
      while(K--){
         Data temp = pq.top();
         pq.pop();
         if(K == 0){
            ret[0] = temp.a;
            ret[1] = temp.b;
            return ret;
         }
         if(temp.idx + 1 < n){
            int idx = temp.idx + 1;
            pq.push(Data(double(A[idx]), double(temp.b), idx));
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,3,5,7};
   print_vector(ob.kthSmallestPrimeFraction(v, 2));
}

Input

{1,3,5,7}
2

Output

[1, 5, ]

Updated on: 02-Jun-2020

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements