Stirling numbers of the second kind: Difference between revisions

m
Simplified code
m (Phix/mpfr)
m (Simplified code)
Line 117:
 
typedef struct stirling_cache_tag {
int nmax;
int* values;
} stirling_cache;
 
boolint stirling_cache_createstirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
int* values = calloc(n * (n + 1)/2, sizeof(int));
return 1;
if (k == 0 || k > n || n > sc->max)
return 0;
return (n > sc->n) ? NULL : &sc->values[n*(n-1)/2 + k - 1];
 
int*bool stirling_cache_getstirling_cache_create(stirling_cache* sc, int n, int kmax) {
int* values = calloc(nmax * (nmax + 1)/2, sizeof(int));
if (values == NULL)
return false;
sc->nmax = nmax;
sc->values = values;
for (int n = 1; n <= max; ++n) {
*valuefor (int k = 1; +k s1< + s2 *n; ++k;) {
int s1 = stirling_number2(sc, n - 1, k - 1);
int s2 = stirling_number2(sc, n - 1, k);
values[n*(n-1)/2 + k - 1] = s1 + s2 * k;
}
}
return true;
}
Line 133 ⟶ 148:
free(sc->values);
sc->values = NULL;
 
int* stirling_cache_get(stirling_cache* sc, int n, int k) {
return (n > sc->n) ? NULL : &sc->values[n*(n-1)/2 + k - 1];
}
 
int stirling_number2(stirling_cache* sc, int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n)
return 0;
int* value = stirling_cache_get(sc, n, k);
if (value == NULL) {
fprintf(stderr, "Cache size is too small\n");
exit(1);
}
if (*value == 0) {
int s1 = stirling_number2(sc, n - 1, k - 1);
int s2 = stirling_number2(sc, n - 1, k);
*value = 1 + s1 + s2 * k;
}
return *value - 1;
}
 
1,777

edits