diff options
| author | Tyge Løvset <[email protected]> | 2023-02-27 19:25:08 +0100 |
|---|---|---|
| committer | Tyge Løvset <[email protected]> | 2023-02-27 19:25:08 +0100 |
| commit | d2228c3dc993e47c8d2df951230cf43a93299f5f (patch) | |
| tree | 03e15c7787946d776b103091d941762ef57850e1 | |
| parent | 400e5bd8ad2b2daef411e5530b6fda6158672829 (diff) | |
| download | STC-modified-d2228c3dc993e47c8d2df951230cf43a93299f5f.tar.gz STC-modified-d2228c3dc993e47c8d2df951230cf43a93299f5f.zip | |
Added example Pythagorean triples. (Arthur O’Dwyer blog)
| -rw-r--r-- | misc/examples/triples.c | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/misc/examples/triples.c b/misc/examples/triples.c new file mode 100644 index 00000000..e85558a3 --- /dev/null +++ b/misc/examples/triples.c @@ -0,0 +1,52 @@ +// https://quuxplusone.github.io/blog/2019/03/06/pythagorean-triples/ + +#include <stc/algo/coroutine.h> +#include <stdio.h> + +void triples_vanilla(int n) { + for (int i = 1, z = 1;; ++z) { + for (int x = 1; x < z; ++x) { + for (int y = x; y < z; ++y) { + if (x*x + y*y == z*z) { + printf("{%d, %d, %d},\n", x, y, z); + if (++i > n) goto done; + } + } + } + } + done:; +} + +struct tricoro { + int cco_state; + int x, y, z; +}; + +bool triples_coro(struct tricoro* t) { + cco_begin(t); + for (t->z = 1;; ++t->z) { + for (t->x = 1; t->x < t->z; ++t->x) { + for (t->y = t->x; t->y < t->z; ++t->y) { + if (t->x*t->x + t->y*t->y == t->z*t->z) { + cco_yield(true); + } + } + } + } + cco_final: + cco_end(false); +} + + +int main() +{ + puts("Vanilla triples:"); + triples_vanilla(20); + + puts("\nCoroutine triples:"); + struct tricoro t = {0}; + int i = 0; + while (i++ < 20 && triples_coro(&t)) + printf("{%d, %d, %d},\n", t.x, t.y, t.z); + triples_coro(cco_stop(&t)); +}
\ No newline at end of file |
