Ugly number JavaThe Ugly number is another special positive number in Java. If a number has only 2, 3, or 5 prime factors and by convention 1 is also included, the number is called Ugly number. Let's take some examples of Ugly numbers.
In Java, there are two ways or methods through which we can find the Nth Ugly number. These methods are as follows:
Let's understand both the methods one by one implement the logic of each one. The simple method using for loopIn this method, we use the loop for each positive number until the Ugly number count is not greater than n. We increment the counter variable when the number is Ugly, and to check whether the number is Ugly or not, we divide the number by the greatest divisible powers of 2, 3, and 5. When the number becomes 1, it is an Ugly number. Otherwise, it is not an Ugly number. Let's implement the code to get Nth Ugly number in Java. UglyNumberExample1.java Output: In the same way, we can also implement the code to check whether the given number is an Ugly number or not. UglyNumberExample2.java Output: Using Dynamic ProgrammingThere is another way of getting the Nth Ugly number that takes O(n) extra space. The series of starting few Ugly numbers is 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …….. We can split the above sequence into tree subsequences in such a way that each group in an ugly sequence like as
In order to get each ugly number from the sequences, we use the merge method as merge sort. These are the following steps which we use to get the Nth ugly number using dynamic programming:
Let's use the above steps and implement the actual code of it in Java. UglyNumberExample3.java Output:
Next TopicAchilles Number in Java
|