Home » Java programs » Java basic programs

Java program to check whether a given number is ugly number or not

Here, we are implementing a java program that will read an integer number and check whether it is an ugly number or not?
Submitted by IncludeHelp, on January 02, 2018

Given an integer number and we have to check whether it is Ugly number or not using java program.

What is Ugly number?

A number is said to be an Ugly number if and only if the number is divisible by 2, 3, and 5. Which means the number is said to be Ugly if its prime factors are 2, 3, and 5.

Example:

    Input:
    Enter a number: 120

    Output:
    The given number is an ugly number.

    Explanation:
    120 is divisible by 2, 3 and 5. Hence, it is Ugly number.

Program to check given number is Ugly number or not using Java program

import java.util.Scanner;

public class CheckUglyNumbers
{
	public static void main(String[] args)
	{
		// create object of scanner class.
		Scanner Sc = new Scanner(System.in);

		// enter the positive number
		System.out.print("Enter the number : ");
		int n = Sc.nextInt();  		
		if (n <= 0)
		{
			System.out.print("Enter correct/+ve number.");
		}
		int x = 0;
		while (n != 1)
		{
			// loop to obtain the result.
			if (n % 5 == 0)
			{
				n /= 5;
			}

			else if (n % 3 == 0) 
			{
				n /= 3;
			}

			else if (n % 2 == 0)
			{
				n /= 2;
			}

			else
			{
				System.out.print("The given number is not a ugly number.");
				x = 1;
				break;
			}
		}
		if (x==0)
			System.out.print("The given number is an ugly number.");
		System.out.print("\n");
	}
}

Output

First run:
Enter the number : 42
The given number is not a ugly number.

Second run:
Enter the number : 120
The given number is an ugly number.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.