summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/triples.c
blob: 4783d6038c464b05fd76a494dfe5aaca0cc8234c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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, c = 1;; ++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;
                }
            }
        }
    }
    done:;
}

struct triples {
    int n;
    int a, b, c;
    int cco_state;
};

bool triples_next(struct triples* I) {
    cco_begin(I);
        for (I->c = 1;; ++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;
                        cco_yield(true);
                    }
                }
            }
        }
        cco_final:
    cco_end(false);
}


int main()
{
    puts("Vanilla triples:");
    triples_vanilla(6);

    puts("\nCoroutine triples:");
    struct triples t = {INT32_MAX};
    while (triples_next(&t)) {
        if (t.c < 100) printf("{%d, %d, %d},\n", t.a, t.b, t.c);
        else cco_stop(&t);
    }
}