Stirling numbers of the second kind: Difference between revisions

Added C solution
(Added C solution)
Line 109:
Maximum Stirling number of the second kind with n = 100:
7769730053598745155212806612787584787397878128370115840974992570102386086289805848025074822404843545178960761551674
</pre>
 
=={{header|C}}==
<lang c>#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
 
typedef struct stirling_cache_tag {
int n;
int* values;
} stirling_cache;
 
bool stirling_cache_create(stirling_cache* sc, int n) {
int* values = calloc(n * (n + 1)/2, sizeof(int));
if (values == NULL)
return false;
sc->n = n;
sc->values = values;
return true;
}
 
void stirling_cache_destroy(stirling_cache* sc) {
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 == 0)
return n == 0 ? 1 : 0;
if (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;
}
 
void print_stirling_numbers(stirling_cache* sc, int max) {
printf("Stirling numbers of the second kind:\nn/k");
for (int k = 0; k <= max; ++k)
printf(k == 0 ? "%2d" : "%8d", k);
printf("\n");
for (int n = 0; n <= max; ++n) {
printf("%2d ", n);
for (int k = 0; k <= n; ++k)
printf(k == 0 ? "%2d" : "%8d", stirling_number2(sc, n, k));
printf("\n");
}
}
 
int main() {
stirling_cache sc = { 0 };
const int max = 12;
if (!stirling_cache_create(&sc, max)) {
fprintf(stderr, "Out of memory\n");
return 1;
}
print_stirling_numbers(&sc, max);
stirling_cache_destroy(&sc);
return 0;
}</lang>
 
{{out}}
<pre>
Stirling numbers of the second kind:
n/k 0 1 2 3 4 5 6 7 8 9 10 11 12
0 1
1 0 1
2 0 1 1
3 0 1 3 1
4 0 1 7 6 1
5 0 1 15 25 10 1
6 0 1 31 90 65 15 1
7 0 1 63 301 350 140 21 1
8 0 1 127 966 1701 1050 266 28 1
9 0 1 255 3025 7770 6951 2646 462 36 1
10 0 1 511 9330 34105 42525 22827 5880 750 45 1
11 0 1 1023 28501 145750 246730 179487 63987 11880 1155 55 1
12 0 1 2047 86526 611501 1379400 1323652 627396 159027 22275 1705 66 1
</pre>
 
1,777

edits