Skip to content

Commit 46f1f50

Browse files
committed
🤢 Ugly Numbers
1 parent ad83388 commit 46f1f50

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Ugly numbers are numbers whose only prime factors are 2, 3 or 5.
3+
*/
4+
5+
import java.util.*;
6+
import java.io.*;
7+
8+
class UglyNumbers {
9+
10+
public static int getNthUglyNumber(int n) {
11+
int array[] = new int[n + 1];
12+
13+
array[0] = 1;
14+
15+
int i2 = 0;
16+
int i3 = 0;
17+
int i5 = 0;
18+
19+
int nextMultipleOf2 = 2;
20+
int nextMultipleOf3 = 3;
21+
int nextMultipleOf5 = 5;
22+
23+
24+
for (int i = 1; i < n; i++) {
25+
26+
int min = Math.min(nextMultipleOf2, Math.min(nextMultipleOf3, nextMultipleOf5));
27+
28+
array[i] = min;
29+
if (min == nextMultipleOf2) {
30+
i2++;
31+
nextMultipleOf2 = array[i2]*2;
32+
}
33+
if (min == nextMultipleOf3) {
34+
i3++;
35+
nextMultipleOf3 = array[i3]*3;
36+
}
37+
if (min == nextMultipleOf5) {
38+
i5++;
39+
nextMultipleOf5 = array[i5]*5;
40+
}
41+
}
42+
return array[n-1];
43+
}
44+
45+
public static void main(String[] args) {
46+
int n = 150;
47+
System.out.println(getNthUglyNumber(n));
48+
}
49+
}

0 commit comments

Comments
 (0)