
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 −
#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
- Related Articles
- Ugly Number in C++
- Super Ugly Number in C++
- Ugly Number III in C++
- Check for Ugly number in JavaScript
- Find the Nth Ugly Number in Java
- Program to find nth ugly number in C++
- Program to check a number is ugly number or not in Python
- Ugly Numbers
- How To Check Whether a Number is an Ugly Number or Not in Java?
- Super Ugly Numbers JavaScript
- Single Number II in Python
- Strobogrammatic Number II in C++
- Confusing Number II in C++
- Maximum length of a sub-array with ugly numbers in C++
- Number of Distinct Islands II in C++
