From d2228c3dc993e47c8d2df951230cf43a93299f5f Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Mon, 27 Feb 2023 19:25:08 +0100 Subject: Added example Pythagorean triples. (Arthur O’Dwyer blog) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- misc/examples/triples.c | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 misc/examples/triples.c 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 +#include + +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 -- cgit v1.2.3