How to find the first 3 primitive Pythagorean triples in Pascal

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)
}

program PrimitivePythagoreanTriples;

{$mode objfpc}{$H+}

uses Math;

{ Compute gcd of two integers }
function gcd(a, b: Integer): Integer;
var
    t: Integer;
begin
    while b <> 0 do
    begin
        t := b;
        b := a mod b;
        a := t;
    end;
    gcd := a;
end;

{ Check if (a, b, c) is a primitive Pythagorean triple }
function isPrimitiveTriple(a, b, c: Integer): Boolean;
begin
    if a*a + b*b <> c*c then
        isPrimitiveTriple := False
    else
        isPrimitiveTriple :=
            (gcd(a, b) = 1) and
            (gcd(b, c) = 1) and
            (gcd(a, c) = 1);
end;

{ Find and print the first 3 primitive Pythagorean triples }
procedure findFirstThreePrimitiveTriples;
var
    a, b, c, count: Integer;
begin
    count := 0;

    for a := 1 to 200 do
    begin
        for b := a + 1 to 200 do
        begin
            c := Trunc(Sqrt(a*a + b*b));

            if c*c = a*a + b*b then
            begin
                if isPrimitiveTriple(a, b, c) then
                begin
                    WriteLn('(', a, ', ', b, ', ', c, ')');
                    Inc(count);

                    if count = 3 then
                        Exit;
                end;
            end;
        end;
    end;
end;

begin
    WriteLn('First 3 primitive Pythagorean triples:');
    findFirstThreePrimitiveTriples;
end.


(*
run:

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

*)

 



answered Jun 19 by avibootz
...