Ugly Number Program in Java with Examples

In this post, I will be sharing what is an Ugly number, examples of Ugly number, algorithm, and java program to check whether a given number is an Ugly number or not.

Read Also: Disarium Number in Java

What is Ugly Number

Ugly numbers are those positive numbers whose only prime factors are 2, 3 or 5.

Examples

Number to check : 10  
Prime Factors : 2,5 
Prime Factors only contain either 2,3 or 5 : Yes // 10 is an Ugly number
 
Number to check : 120  
Prime Factors : 2,3,5
Prime Factors only contain either 2,3 or 5 : Yes // 120 is an Ugly number

Below are examples of numbers that are NOT Ugly numbers.

Number to check : 19  
Prime Factors : 19
Prime Factors only contain either 2,3 or 5 : No // 19 is NOT an Ugly number
 
Number to check : 42  
Prime Factors : 2,3,7
Prime Factors only contain either 2,3 or 5 : No // 42 is NOT an Ugly number

List of Ugly numbers from 1 to 10 are: 1, 2, 3, 4, 5, 6, 8, 9, 10

Read Also: Happy Number in Java

Java Program for Ugly Number

import java.util.Scanner; 
 
public class JavaHungry {
public static void main(String args[])
{
System.out.println("Enter any number: ");
Scanner scan = new Scanner(System.in);
// Store the input number
Integer inputNumber = scan.nextInt();
checkUglyNumber(inputNumber);
}

public static void checkUglyNumber(Integer inputNumber)
{
int num = inputNumber;
/* Loop will run until
num becomes 1 */
while(num != 1)
{
if (num % 2 == 0)
num /= 2;
else if (num % 3 == 0)
num /= 3;
else if (num % 5 == 0)
num /= 5;
else
{
System.out.println(inputNumber + " is NOT an Ugly Number");
/* Come out of the loop,
method has void return type */
return;
}
}
System.out.println(inputNumber + " is an Ugly Number");
}
}

Output:
Enter any number: 
90
90 is an Ugly Number

Algorithm for Ugly Number

1. Store the inputNumber in num variable.
2. Using while loop
    a. Continue if 2, 3 or 5 are the factors of num.
    b. Break the loop and return empty if num has prime factors other than 2, 3 or 5.  
3. If num value becomes 1 during while loop then print inputNumber is an Ugly number. 

That's all for this post. Please mention in comments in case you have any questions related to the ugly number in java with examples.

You may also like:

Evil number program in Java (solution)
Duck number program in Java (answer)
Bouncy number program in Java (answer)
Perfect number program in Java (solution)
Happy number program in Java (answer)
Magic number program in Java (solution)
Neon number program in Java (solution)
Special number program in Java (solution)
Pronic number program in Java (answer)

0 Comments