1#include <stdio.h>
2#include <stdlib.h>
3
4int collatz(int a) {
5 if (a % 2 == 0)
6 return a / 2;
7 return 3 * a + 1;
8}
9
10void collatzSequence(char *buf, int a) {
11 int offset = sprintf(buf, "%d: ", a);
12 for (int i = a; i >= 1; i = collatz(i)) {
13 if (i == 1) {
14 sprintf(buf + offset, "1");
15 break;
16 }
17 offset += sprintf(buf + offset, "%d, ", i);
18 }
19}
20
21int main(void) {
22 char *buf = malloc(sizeof(char) * 8192);
23 for (int i = 1; i <= 10000; i++) {
24 collatzSequence(buf, i);
25 if (buf == NULL) {
26 fprintf(stderr, "memory allocation failed");
27 return 1;
28 }
29 puts(buf);
30 }
31 free(buf);
32 return 0;
33}