Ugly Numbers

Ugly numbers are those number whose prime factors are 2, 3 or 5. From 1 to 15, there are 11 ugly numbers 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15. The numbers 7, 11, 13 are not ugly because they are prime. The number 14 is not ugly because in its prime factor the 7 will come.

In this program, we will try to find the nth ugly number.

Input and Output

Input:
Take the term number. Say it is 10
Output:
The 10th ugly number is 12

Algorithm

getUglyNumbers(n)

Input: The number of terms.

Output: Find nth Ugly numbers.

Begin
   define array named uglyNum of size n
   i2 := 0, i3 := 0, i5 := 0
   next2mul := 2, next3mul := 3, next5Mul := 5
   next := 1
   ugluNum[0] := 1

   for i := 1 to n, do
      next := minimum of next2Mul, next3Mul and next5Mul
      uglyNum[i] := next
      if next = next2Mul, then
         i2 := i2 + 1
         next2mul := uglyNum[i2] * 2
      if next = next3Mul, then
         i3 := i3 + 1
         next3mul := uglyNum[i3] * 3
      if next = next5Mul, then
         i5 := i5 + 1
         next5mul := uglyNum[i5] * 5
   done
   return next
End

Example

# include
using namespace std;

int min(int x, int y, int z) {            //find smallest among three numbers
   if(x > n;
   cout 

Output

Enter term: 10
10th Ugly number is: 12
Updated on: 2020-06-17T08:04:29+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements