# Program to find nth ugly number in C++

C++Server Side ProgrammingProgramming

Suppose we have a number n; we have to find the nth ugly number. 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, the output will be 12, as the first few ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 and so on.

To solve this, we will follow these steps:

• Define an array v of size(n + 1)
• if n is same as 1, then:
• return 1
• two := 2, three := 3, five := 5
• twoIdx := 2, threeIdx := 2, fiveIdx := 2
• for initialize i := 2, when i <= n, update (increase i by 1), do:
• curr := minimum of two, three and five
• v[i] := curr
• if curr is same as two, then:
• two := v[twoIdx] * 2;
• (increase twoIdx by 1)
• if curr is same as three, then:
• three := v[threeIdx] * 3
• (increase threeIdx by 1)
• if curr is same as five, then:
• five := v[fiveIdx] * 5
• (increase fiveIdx by 1)
• return v[n]

Let us see the following implementation to get better understanding:

## Example

Live Demo

#include
using namespace std;
class Solution {
public:
int nthUglyNumber(int n) {
vector 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(15));
}

## Input

15

## Output

24
Published on 26-Nov-2020 08:05:16