forked from hrsvrdhn/DP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumberDivisbleBy2,3,5
52 lines (47 loc) · 1.58 KB
/
numberDivisbleBy2,3,5
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, number divisible by 2,3 and 5 only
import java.lang.Math;
class UglyNumber
{
/* Function to get the nth ugly number*/
int getNthUglyNo(int n)
{
int ugly[] = new int[n]; // To store ugly numbers
int i2 = 0, i3 = 0, i5 = 0;
int next_multiple_of_2 = 2;
int next_multiple_of_3 = 3;
int next_multiple_of_5 = 5;
int next_ugly_no = 1;
ugly[0] = 1;
for(int i = 1; i < n; i++)
{
next_ugly_no = Math.min(next_multiple_of_2,
Math.min(next_multiple_of_3,
next_multiple_of_5));
ugly[i] = next_ugly_no;
if (next_ugly_no == next_multiple_of_2)
{
i2 = i2+1;
next_multiple_of_2 = ugly[i2]*2;
}
if (next_ugly_no == next_multiple_of_3)
{
i3 = i3+1;
next_multiple_of_3 = ugly[i3]*3;
}
if (next_ugly_no == next_multiple_of_5)
{
i5 = i5+1;
next_multiple_of_5 = ugly[i5]*5;
}
} /*End of for loop (i=1; i<n; i++) */
return next_ugly_no;
}
/* Driver program to test above functions */
public static void main(String args[])
{
Scanner sc= new Scanner (System.in);
int n = sc.nextInt();
UglyNumber obj = new UglyNumber();
System.out.println(obj.getNthUglyNo(n));
}
}