- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find nth ugly number in C++

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 10^{th} 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

#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

- Related Questions & Answers
- Find the Nth Ugly Number in Java
- Program to find Nth Fibonacci Number in Python
- C++ program to find Nth Non Fibonacci Number
- Program to find Nth Even Fibonacci Number in C++
- Ugly Number in C++
- 8085 program to find nth power of a number
- Program to check a number is ugly number or not in Python
- Ugly Number III in C++
- Super Ugly Number in C++
- Ugly Number II in C++
- Find nth Hermite number in C++
- Check for Ugly number in JavaScript
- Nth Catalan Number in Python Program
- Program to find last two digits of Nth Fibonacci number in C++
- Program to find nth smallest number from a given matrix in Python

Advertisements