How to find the first 3 primitive Pythagorean triples in C

1 Answer

0 votes
/*
    A Pythagorean triple is a set of three positive integers (a, b, c)
    that satisfy the equation:

            a^2 + b^2 = c^2

    These represent the side lengths of a right‑angled triangle.

    A *primitive* Pythagorean triple is one in which:
        - gcd(a, b, c) = 1 (no common divisor greater than 1)
        - a, b, and c are positive integers
        - a < b < c

    Examples of primitive triples include:
        (3, 4, 5)
        (5, 12, 13)
        (8, 15, 17)
*/

#include <stdio.h>
#include <math.h>

/* Compute gcd of two integers */
int gcd(int a, int b) {
    while (b != 0) {
        int t = b;
        b = a % b;
        a = t;
    }
    return a;
}

/* Check if (a, b, c) is a primitive Pythagorean triple */
int isPrimitiveTriple(int a, int b, int c) {
    if (a*a + b*b != c*c)
        return 0;

    return gcd(a, b) == 1 && gcd(b, c) == 1 && gcd(a, c) == 1;
}

/* Find and print the first 3 primitive Pythagorean triples */
void findFirstThreePrimitiveTriples() {
    int count = 0;

    for (int a = 1; a < 200; a++) {
        for (int b = a + 1; b < 200; b++) {
            int c = (int)sqrt(a*a + b*b);

            if (c*c == a*a + b*b) {
                if (isPrimitiveTriple(a, b, c)) {
                    printf("(%d, %d, %d)\n", a, b, c);
                    count++;

                    if (count == 3)
                        return;
                }
            }
        }
    }
}

int main() {
    printf("First 3 primitive Pythagorean triples:\n");
    
    findFirstThreePrimitiveTriples();
    
    return 0;
}



/*
run:

First 3 primitive Pythagorean triples:
(3, 4, 5)
(5, 12, 13)
(7, 24, 25)

*/

 



answered 3 days ago by avibootz
...