diff options
| author | realtradam <[email protected]> | 2023-04-12 15:55:33 -0400 |
|---|---|---|
| committer | realtradam <[email protected]> | 2023-04-12 15:55:33 -0400 |
| commit | 0841165881871ee01b782129be681209aeed2423 (patch) | |
| tree | 8a76b61dcaab381b6b42305201ae8b6259f6b6c0 /misc/examples/triples.c | |
| parent | 554f3e8acf7855b5d6a90cc68cefb7445460b03c (diff) | |
| parent | 0516aa3ae823ed9a22b2c5f776948c8447c32c31 (diff) | |
| download | STC-modified-0841165881871ee01b782129be681209aeed2423.tar.gz STC-modified-0841165881871ee01b782129be681209aeed2423.zip | |
Merge branch 'master' into modified
Diffstat (limited to 'misc/examples/triples.c')
| -rw-r--r-- | misc/examples/triples.c | 37 |
1 files changed, 26 insertions, 11 deletions
diff --git a/misc/examples/triples.c b/misc/examples/triples.c index 4783d603..520bf012 100644 --- a/misc/examples/triples.c +++ b/misc/examples/triples.c @@ -4,12 +4,12 @@ #include <stdio.h> void triples_vanilla(int n) { - for (int i = 1, c = 1;; ++c) { + for (int c = 5; n; ++c) { for (int a = 1; a < c; ++a) { - for (int b = a; b < c; ++b) { - if (a*a + b*b == c*c) { - printf("{%d, %d, %d},\n", a, b, c); - if (++i > n) goto done; + for (int b = a + 1; b < c; ++b) { + if ((int64_t)a*a + (int64_t)b*b == (int64_t)c*c) { + printf("{%d, %d, %d}\n", a, b, c); + if (--n == 0) goto done; } } } @@ -25,20 +25,29 @@ struct triples { bool triples_next(struct triples* I) { cco_begin(I); - for (I->c = 1;; ++I->c) { + for (I->c = 5; I->n; ++I->c) { for (I->a = 1; I->a < I->c; ++I->a) { - for (I->b = I->a; I->b < I->c; ++I->b) { - if (I->a*I->a + I->b*I->b == I->c*I->c) { - if (I->n-- == 0) cco_return; + for (I->b = I->a + 1; I->b < I->c; ++I->b) { + if ((int64_t)I->a*I->a + (int64_t)I->b*I->b == (int64_t)I->c*I->c) { cco_yield(true); + if (--I->n == 0) cco_return; } } } } cco_final: + puts("done"); cco_end(false); } +int gcd(int a, int b) { + while (b) { + int t = a % b; + a = b; + b = t; + } + return a; +} int main() { @@ -47,8 +56,14 @@ int main() puts("\nCoroutine triples:"); struct triples t = {INT32_MAX}; + int n = 0; + while (triples_next(&t)) { - if (t.c < 100) printf("{%d, %d, %d},\n", t.a, t.b, t.c); - else cco_stop(&t); + if (gcd(t.a, t.b) > 1) + continue; + if (t.c < 100) + printf("%d: {%d, %d, %d}\n", ++n, t.a, t.b, t.c); + else + cco_stop(&t); } } |
