Q:

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

belongs to collection: Java Basic Programs

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to check whether given number is Kapr... >>
<< Java program to generate random numbers between gi...