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.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.