A number whose prime factors are either 2, 3 or 5 is called an Ugly Number. Some of the ugly numbers are: 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, etc.
We have a number N and the task is to find the Nth Ugly number in the sequence of Ugly numbers.
For Example:
Input-1:
N = 5
Output:
5
Explanation:
The 5th ugly number in the sequence of ugly numbers [1, 2, 3, 4, 5, 6, 8, 10, 12, 15] is 5.
Input-2:
N = 7
Output:
8
Explanation:
The 7th ugly number in the sequence of ugly numbers [1, 2, 3, 4, 5, 6, 8, 10, 12, 15] is 8.
Approach to Solve this Problem
A simple approach to solve this problem is to check if the given number is divisible by 2 or 3 or 5 and keep track of the sequence till the given number. Now find if the number satisfies all the condition of an ugly number, then return the number as the output.
- Take input of a number N to find the Nth Ugly Number.
- A Boolean function isUgly(int n) takes a number ‘n’ as the input and returns True if it is an ugly number, otherwise False.
- An integer function findNthUgly(int n) takes ‘n’ number as the input and returns the nth ugly number as the output.
Example
public class UglyN { public static boolean isUglyNumber(int num) { boolean x = true; while (num != 1) { if (num % 5 == 0) { num /= 5; } else if (num % 3 == 0) { num /= 3; } // To check if number is divisible by 2 or not else if (num % 2 == 0) { num /= 2; } else { x = false; break; } } return x; } public static int nthUglyNumber(int n) { int i = 1; int count = 1; while (n > count) { i++; if (isUglyNumber(i)) { count++; } } return i; } public static void main(String[] args) { int number = 100; int no = nthUglyNumber(number); System.out.println("The Ugly no. at position " + number + " is " + no); } }
Output
The Ugly no. at position 100 is 1536.