Ugly Number II in C++


Suppose we have to find the nth ugly number, so we have to define a method that can find it. As we know that the ugly numbers are those numbers, whose prime factors are only 2, 3 and 5. So if we want to find 10th ugly number, that will be 12, as the first few ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12

To solve this, we will follow these steps −

  • Make an array v, of size n + 1

  • if n = 1, then return 1

  • two := 2, three = 3 and five = 5, towIndex := 2, threeIndex := 2 and fiveIndex := 2

  • for i in range 2 to n

    • curr := min of two, three and five

    • v[i] := curr

    • if curr = two, then two := v[twoIndex] * 2, increase twoIndex by 1

    • if curr = three, then three := v[threeIndex] * 3, increase threeIndex by 1

    • if curr = five, then five := v[fiveIndex] * 3, increase fiveIndex by 1

  • 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;
class Solution {
   public:
   int nthUglyNumber(int n) {
      vector <int> v(n + 1);
      if(n == 1){
         return 1;
      }
      int two = 2, three = 3, five = 5;
      int twoIdx = 2;
      int threeIdx = 2;
      int fiveIdx = 2;
      for(int i = 2; i <= n; i++){
         int curr = min({two, three, five});
         v[i] = curr;
         if(curr == two){
            two = v[twoIdx] * 2;;
            twoIdx++;
         }
         if(curr == three){
            three = v[threeIdx] * 3;
            threeIdx++;
         }
         if(curr == five){
            five = v[fiveIdx] * 5;
            fiveIdx++;
         }
      }
      return v[n];
   }
};
main(){
   Solution ob;
   cout << (ob.nthUglyNumber(10));
}

Input

10

Output

12

Updated on: 02-May-2020

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements