Super Ugly Number in C++


We have to create one function to find the nth super ugly number. The super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. So if the n is 12 and primes are [2, 7, 13, 19], then the output will be 32, this is because [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of 12 super ugly numbers.

To solve this, we will follow these steps −

  • Create a data structure triplet, with num, prime and idx

  • if n is 1, then return 1, create an array of size n + 1, and fill this with 1

  • define a priority queue pq

  • for i in range 0 to size of primes−

    • create triplets t(primes[i], primes[i], 2)

  • for i in range 2 to n

    • curr := top element of pq, then delete from pq

    • val := num of curr

    • v[i] := val

    • num of curr := prime of curr * v[index of curr]

    • increase index of curr by 1

    • insert curr into pq

    • while val = num of pq top,

      • curr := top of pq and delete from pq

      • num of curr := prime of curr * v[index of curr]

      • increase index of curr by 1

      • insert curr into pq

  • return v[n]

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Data{
   int num, prime, idx;
   Data(int a, int b, int c){
      num = a;
      prime = b;
      idx = c;
   }
};
struct Comparator{
   bool operator()(Data a, Data b){
      return !(a.num < b.num);
   }
};
class Solution {
   public:
   int nthSuperUglyNumber(int n, vector<int>& primes) {
      if(n == 1)return 1;
      vector <int> v(n + 1, 1);
      priority_queue < Data, vector < Data >, Comparator > pq;
      for(int i = 0; i < primes.size(); i++){
         pq.push(Data(primes[i], primes[i], 2));
      }
      int x;
      for(int i = 2; i <= n; i++){
         Data curr = pq.top();
         pq.pop();
         int val = curr.num;
         v[i] = val;
         curr.num = curr.prime * v[curr.idx];
         curr.idx++;
         pq.push(curr);
         while(val == pq.top().num){
            curr = pq.top();
            pq.pop();
            curr.num = curr.prime * v[curr.idx];
            curr.idx++;
            pq.push(curr);
         }
      }
      return v[n];
   }
};
main(){
   Solution ob;
   vector<int> v = {2,7,13,19};
   cout << (ob.nthSuperUglyNumber(12, v));
}

Input

12
[2,7,13,19]

Output

32

Updated on: 29-Apr-2020

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements