-
Notifications
You must be signed in to change notification settings - Fork 118
/
313.c
48 lines (37 loc) · 1.02 KB
/
313.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
int nthSuperUglyNumber(int n, int* primes, int primesSize) {
if (n <= 0 || primesSize <= 0) return 1;
int *index = (int *)calloc(primesSize, sizeof(int));
int *nums = (int *)calloc(n, sizeof(int));
nums[0] = 1;
int storageIndex = 1;
while (storageIndex < n) {
int min = INT32_MAX;
int i;
for (i = 0; i < primesSize; i++) {
if (nums[index[i]] * primes[i] < min) {
min = nums[index[i]] * primes[i];
}
}
nums[storageIndex++] = min;
for (i = 0; i < primesSize; i++) {
if (nums[index[i]] * primes[i] == min) {
index[i]++;
}
}
}
int ans = nums[n - 1];
free(index);
free(nums);
return ans;
}
int main() {
int n = 3;
int primes[] = { 2, 3, 5 };
assert(nthSuperUglyNumber(n, primes, sizeof(primes)/sizeof(primes[0])) == 3);
printf("all tests passed!\n");
return 0;
}