# Finding Ugly Number using Dynamic Programming (DP)

Here, we are going to learn **what ugly number is** and **how to find ugly number using dynamic programming (DP)**?

Submitted by Ritik Aggarwal, on December 11, 2018

**Problem:** You are given **N**. You have to find **N ^{th}** ugly number.

**1**ugly number is

^{st}**1**.

**Constraints:** 1 <= N <= 10000

**Examples:**

Input: 10 Output: 10^{th}ugly number is 12 Input: 724 Output: 724^{th}ugly number is 7085880

**Explanation of the problem:**

**Ugly numbers** are those number whose only prime factors are **2, 3, 5 (except 1)**. **1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...**, So our **10 ^{th}** ugly number is

**12**.

**Solution:**

The basic and the brute force approach for solving this problem is to iterate over all the numbers and check whether it is ugly or not then incrementing the counter but this approach will be highly inefficient to solve. Therefore, we will discuss the Dynamic Programming approach. Now we will take a dp matrix in which **i ^{th}** cell represent ith ugly number. Then we will find the answer to ugly number using this dp relation.

**Ugly number(i) = minimum of (2*ugly number(f2), 3*ugly number(f3), 5*ugly number(f5))**

Where, **f2**, **f3**, **f5** are counters for **2**, **3**, **5** respectively which stores the index for **f2 ^{th}** ugly number,

**f3**ugly number,

^{th}**f5**ugly number.

^{th}Then we will store our answer.

## Algorithm

- Initializing
**f2**,**f3**,**f5**to maintain**f2**ugly number,^{th}**f3**ugly number and^{th}**f5**ugly number to^{th}**1**. - Creating a DP matrix in which ith cell represent
**i**ugly number.^{th} - Start filling the dp matrix from
**i = 2**. - Ugly
**number(i) = minimum of (2*ugly number(f2), 3*ugly number(f3), 5*ugly number(f5))**. - Finding the answer using above relation and storing it at
**i**index.^{th}

**Now, the time complexity of the above code is O(N).**

**Program:**

#include <iostream> using namespace std; long long int uglyNumber(int n){ // f2 maintains the index of the ugly number // for multiplication by 2 int f2 = 1; // f3 maintains the index of the ugly number // for multiplication by 3 int f3 = 1; // f5 maintains the index of the ugly number // for multiplication by 5 int f5 = 1; long long int dp[n + 1] = {0}; // first ugly number is 1 dp[1] = 1; // filling the dp matrix from i = 2 for(int i = 2;i<=n;i++){ // calculating the next number from previous ugly numbers long long int ans_f_2 = dp[f2] * 2; long long int ans_f_3 = dp[f3] * 3; long long int ans_f_5 = dp[f5] * 5; // finding minimum of all the answer long long int final_ans = min(ans_f_2, min(ans_f_3, ans_f_5)); // storing the ans dp[i] = final_ans; // if our final_ans is ans_f_2, ans_f_3, ans_f_5 // then increment their counters i.e f2, f3, f5 if(final_ans == ans_f_2){ f2++; } if(final_ans == ans_f_3){ f3++; } if(final_ans == ans_f_5){ f5++; } } return dp[n]; } // driver program to check the code int main() { int n; cin >> n; cout << n << endl; cout<< n << "th ugly number is " <<uglyNumber(n) << endl; return 0; }

**Output**

10 10 10th ugly number is 12

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Bubble sort Algorithm, Flow Chart and C++ Code
- Insertion sort Algorithm, flowchart and C, C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Meta Binary Search | One-sided Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Find the Nth Fibonacci number | C++
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Egg dropping problem using Dynamic Programming (DP)
- Wild card matching problem using Dynamic programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

Comments and Discussions!