The Ada Program: pythagorean.adb

  1 -- pythagorean.adb:  search for pythagorean triples up to N
  2 
  3 -- A pythagorean triple (A,B,C) has the property that A**2+B**2 = C**2.
  4 -- Note:  if (A,B,C) is a pythagorean triple, then so is (B,A,C).
  5 -- Also:  there are no pythagorean triples of the form (A,A,C).
  6 
  7 with
  8   Ada.Command_Line,     -- access to external execution env (Ada95 A.15)
  9   Ada.Text_IO,          -- usual text (Latin 1) input/output (A.10.1)
 10   Ada.Integer_Text_IO;  -- preinstantiated generic for Integer IO
 11 use Ada;
 12 
 13 procedure Pythagorean is
 14 
 15    Arg: constant String := Command_Line.Argument (1);
 16    N  : Integer;   -- (from the user) maximum number allowed in triple
 17    L  : Positive;  -- last postion in string (ignored)
 18 
 19 begin
 20 
 21    -- Convert the first command line argument (a string) to an integer
 22    Integer_Text_IO.Get (From=>Arg, Item=>N, Last=>L);
 23 
 24    -- Since a**2+b**2=b**2+a**2, we might as well assume a<b
 25    -- (a /= b since 2*a**2=c**2 is impossible for whole numbers),
 26    -- since a,b<c, we begin searching at b+1.
 27 
 28    for A in 1 .. N loop
 29       for B in A+1 .. N loop
 30          for C in B+1 .. N loop
 31             if (A**2+B**2 = C**2) then
 32                -- established (A,B,C) is a pythagorean triple
 33                Integer_Text_IO.Put (A, Width=>0);
 34                Text_IO.Put (", ");
 35                Integer_Text_IO.Put (B, Width=>0);
 36                Text_IO.Put (", ");
 37                Integer_Text_IO.Put (C, Width=>0);
 38                Text_IO.New_Line;
 39             end if;
 40          end loop;
 41       end loop;
 42    end loop;
 43 
 44 end Pythagorean;