summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/triples.c
diff options
context:
space:
mode:
authorTyge Løvset <[email protected]>2023-05-04 11:51:56 +0200
committerTyge Løvset <[email protected]>2023-05-04 16:19:00 +0200
commitb03148caa1d6fc660e6e7c5986dd6fd38779bedc (patch)
tree6e4c7972437f6e8e6fddf39b0f48a2b0ace05af8 /misc/examples/triples.c
parent6b23e35287f26dad63abd755c5f365b443e025a3 (diff)
downloadSTC-modified-b03148caa1d6fc660e6e7c5986dd6fd38779bedc.tar.gz
STC-modified-b03148caa1d6fc660e6e7c5986dd6fd38779bedc.zip
Updates in coroutines.h: No longer *required* with cco_final:, but only when no cleanup is needed.
Diffstat (limited to 'misc/examples/triples.c')
-rw-r--r--misc/examples/triples.c46
1 files changed, 24 insertions, 22 deletions
diff --git a/misc/examples/triples.c b/misc/examples/triples.c
index 2e0211c3..183b7389 100644
--- a/misc/examples/triples.c
+++ b/misc/examples/triples.c
@@ -3,12 +3,21 @@
#include <stc/algo/coroutine.h>
#include <stdio.h>
+int gcd(int a, int b) {
+ while (b) {
+ int t = a % b;
+ a = b;
+ b = t;
+ }
+ return a;
+}
+
void triples_vanilla(int n) {
- for (int c = 5; n; ++c) {
+ for (int c = 5, i = 0; n; ++c) {
for (int a = 1; a < c; ++a) {
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 ((int64_t)a*a + (int64_t)b*b == (int64_t)c*c && gcd(a, b) == 1) {
+ printf("%d: {%d, %d, %d}\n", ++i, a, b, c);
if (--n == 0) goto done;
}
}
@@ -18,41 +27,34 @@ void triples_vanilla(int n) {
}
struct triples {
- int n;
+ int size, count;
int a, b, c;
int cco_state;
};
-bool triples_coro(struct triples* I) {
- cco_begin(I);
- for (I->c = 5; I->n; ++I->c) {
- for (I->a = 1; I->a < I->c; ++I->a) {
- 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) {
+bool triples_coro(struct triples* t) {
+ cco_begin(t);
+ t->count = 0;
+ for (t->c = 5; t->size; ++t->c) {
+ for (t->a = 1; t->a < t->c; ++t->a) {
+ for (t->b = t->a + 1; t->b < t->c; ++t->b) {
+ if ((int64_t)t->a*t->a + (int64_t)t->b*t->b == (int64_t)t->c*t->c) {
+ if (t->count++ == t->size)
+ cco_return;
cco_yield(false);
- if (--I->n == 0) cco_return;
}
}
}
}
- cco_final:
+ cco_final:
puts("done");
cco_end(true);
}
-int gcd(int a, int b) {
- while (b) {
- int t = a % b;
- a = b;
- b = t;
- }
- return a;
-}
-
int main()
{
puts("Vanilla triples:");
- triples_vanilla(6);
+ triples_vanilla(5);
puts("\nCoroutine triples:");
struct triples t = {INT32_MAX};