-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathUgly_numbers.java
53 lines (44 loc) · 850 Bytes
/
Ugly_numbers.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
// Java program to find nth ugly number
class GFG {
/*This function divides a by greatest
divisible power of b*/
static int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}
/* Function to check if a number
is ugly or not */
static int isUgly(int no)
{
no = maxDivide(no, 2);
no = maxDivide(no, 3);
no = maxDivide(no, 5);
return (no == 1) ? 1 : 0;
}
/* Function to get the nth ugly
number*/
static int getNthUglyNo(int n)
{
int i = 1;
// ugly number count
int count = 1;
// check for all integers
// until count becomes n
while (n > count) {
i++;
if (isUgly(i) == 1)
count++;
}
return i;
}
/* Driver Code*/
public static void main(String args[])
{
int no = getNthUglyNo(150);
// Function call
System.out.println("150th ugly "
+ "no. is " + no);
}
}