3 /* SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
17 enum { PASCALS_TRIANGLE_MAX_ROWS_FOR_UINT64
= 68 };
19 static inline size_t cord(size_t a
, size_t b
)
21 return a
* (a
+ 1) / 2 + b
;
24 static uint64_t *create_pascals_triangle(size_t num_rows
)
29 if (!num_rows
|| num_rows
> PASCALS_TRIANGLE_MAX_ROWS_FOR_UINT64
) {
34 triangle
= reallocarray(NULL
, cord(num_rows
, 0), sizeof(*triangle
));
38 for (i
= 0; i
< num_rows
; ++i
) {
39 triangle
[cord(i
, 0)] = triangle
[cord(i
, i
)] = 1;
40 for (j
= 1; j
< i
; ++j
)
41 triangle
[cord(i
, j
)] = triangle
[cord(i
- 1, j
- 1)] + triangle
[cord(i
- 1, j
)];
47 static void print_pascals_triangle(FILE *file
, const uint64_t *triangle
, size_t num_rows
)
51 for (i
= 0; i
< num_rows
; ++i
) {
52 for (j
= 0; j
< i
+ 1; ++j
)
53 fprintf(file
, "%" PRIu64
" ", triangle
[cord(i
, j
)]);
58 int main(int argc
, char *argv
[])
65 fprintf(stderr
, "Usage: %s ROWS\n", argv
[0]);
69 num_rows
= strtoul(argv
[1], &endptr
, 10);
70 if (!*argv
[1] || *endptr
) {
71 fprintf(stderr
, "ERROR: `%s' is not a valid number\n", argv
[1]);
75 triangle
= create_pascals_triangle(num_rows
);
77 perror("ERROR: unable to create triangle");
80 print_pascals_triangle(stdout
, triangle
, num_rows
);