Find Nth Ugly Number

Given a number N, we have to write a code to find the Nth ugly number.

What is Ugly Numbers?

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. In simple words, The number which can be represented as the product of 2, 3 and 5 are ugly numbers (2^i * 3^i * 5^i).

For Example –

Input : n = 10, Output : 12

12 is the 10th ugly number. The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12.

Note:  

1 is typically treated as an ugly number.

n does not exceed 1690.

In this tutorial, I am going to discuss multiple approaches to solve this problem.

Programming questions on Binary Search

Programming questions on binary trees

Programming Video Tutorials

Ugly Numbers – Java Code

The simplest approach to solve this problem is to run a loop from 1 until the nth ugly number is found.

How do we check whether a number is ugly or not?  

Take a number, divide the number by greatest divisible powers of 2, 3 and 5,  if the number becomes 1 then it is an ugly number otherwise not.

Find Nth Ugly Number using Dynamic Programming – Java Code

We know the first ugly number is 1, We can generate the next ugly numbers by multiplying 2,3,5 with the previous ugly number.

So after 1 the next ugly number will be the Min of the multiple of 2, 3, 5 with 1. It is 2. Similarly, we can calculate next ugly number and so on.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.