In this tutorial you will learn about the Program to check Ugly Number in Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Ugly Number in Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
- User define functions.
What is Ugly Numbers?
Ugly numbers is a number whose prime factors are “2, 3 or 5“. Some of the Ugly number are as “1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15”. So the number after dividing gives factors either 2,3 or 5, are called Ugly number.
Program to check Ugly Number in Java
In this program , we will learn to create a Program to check Ugly Number.First we would declared and initialized the required variables. Next, we would prompt user to input the values. Later we will find that they the number is Ugly or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// java program to find ugly number.. public class UglyNo { public static boolean UglyNumber(int no) { boolean x = true; while (no != 1) { if (no % 5 == 0) { no /= 5; } else if (no % 3 == 0) { no /= 3; } // To check if number is divisible by 2 or not else if (no % 2 == 0) { no /= 2; } else { x = false; break; } } return x; } public static int UglyNum(int n) { int i = 1; int count = 1; while (n > count) { i++; if (UglyNumber(i)) { count++; } } return i; } public static void main(String[] args) { int number = 50; int no = UglyNum(number); System.out.println("The Ugly no. at position " + number + " is " + no); } } |
output
In the above program, we have first declared and initialized a set variables required in the program.
- number= A number N to find the Nth Ugly Number.
- no2= it will hold second entered number.
- sum1= it will calculate first divisor’s sum.
- sum2= it will calculate second divisor’s sum.
- i = for iteration.
After that taking values from user we will assigned these values in to variable “no1” and “no2” respectively.
So what we are do here is that if any number has factor 2,3, or 5 if it has then the number is ugly and if number not have factors 2,3 or 5 then it is not ugly.Let’s take an example for that
Number is : 10
So Prime Factors of 10 is : 2 and 5.
Prime Factors contains only 2,3 or 5 : Here 10 is an Ugly number.
Number is : 11
So Prime Factors of 11 is : 1 and 11.
Prime Factors contains only 2,3 or 5 : Here 11 is not an Ugly number.
so here we have done same using java programming in image below .
So finding that the number is Ugly or not, we divide the number by 2, 3, and 5. When the number gives remainder equivalent to Zero,then it is an Ugly number. Otherwise, it is not an Ugly number.