-
Notifications
You must be signed in to change notification settings - Fork 6
/
34_UglyNumber.cpp
86 lines (69 loc) · 1.39 KB
/
34_UglyNumber.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <cstdio>
using namespace std;
bool IsUglyNumber(int number)
{
if (number <= 0)
return false;
while (number % 2 == 0)
number = number / 2;
while (number % 3 == 0)
number = number / 3;
while (number % 5 == 0)
number = number / 5;
return (number == 1) ? true : false;
}
int GetUglyNumber(int n)
{
int count = 0, number = 0;
if (n <= 0)
return 0;
while (count < n)
{
++number;
if (IsUglyNumber(number))
++ count;
}
return number;
}
int Min(int a, int b, int c)
{
int min = (a < b) ? a : b;
min = (min < c) ? min : c;
return min;
}
int GetUglyNumber2(int n)
{
if (n <= 0)
return 0;
int *pUglyNumber = new int[n];
pUglyNumber[0] = 1; //first uglynumber is 1
int nexUnglyIndex = 1;
int *pMultiply2 = pUglyNumber;
int *pMultiply3 = pUglyNumber;
int *pMultiply5 = pUglyNumber;
while (nexUnglyIndex < n)
{
pUglyNumber[nexUnglyIndex] = Min(*pMultiply2 * 2, *pMultiply3 * 3, *pMultiply5 * 5);
while (*pMultiply2 * 2 <= pUglyNumber[nexUnglyIndex])
++pMultiply2;
while (*pMultiply3 * 3 <= pUglyNumber[nexUnglyIndex])
++pMultiply3;
while (*pMultiply5 * 5 <= pUglyNumber[nexUnglyIndex])
++pMultiply5;
++ nexUnglyIndex;
}
int ugly = pUglyNumber[nexUnglyIndex - 1];
delete[] pUglyNumber;
return ugly;
}
int main(void)
{
int n, number = 0;
while (cin >> n)
{
number = GetUglyNumber2(n);
printf("%d\n", number);
}
return 0;
}