Heronian triangles: Difference between revisions

m
m (→‎{{header|REXX}}: added whitespace to compensate for no previous PRE html tag.)
m (→‎{{header|Wren}}: Minor tidy)
 
(126 intermediate revisions by 34 users not shown)
Line 1:
{{task}}
[[wp:Heron's formula|Hero's formula]] for the area of a triangle given the length of its three sides
''a'', ''b'', and ''c'' is given by:
 
[[wp:Heron's formula|Hero's formula]] for the area of a triangle given the length of its three sides &nbsp; <big> ''a'',</big> &nbsp; <big>''b'',</big> &nbsp; and &nbsp; <big>''c''</big> &nbsp; is given by:
:<math>A = \sqrt{s(s-a)(s-b)(s-c)},</math>
 
:::: <big><math>A = \sqrt{s(s-a)(s-b)(s-c)},</math></big>
where ''s'' is half the perimeter of the triangle; that is,
 
where &nbsp; <big>''s''</big> &nbsp; is half the perimeter of the triangle; that is,
:<math>s=\frac{a+b+c}{2}.</math>
 
:::: <big><math>s=\frac{a+b+c}{2}.</math></big>
 
<br>
'''[http://www.had2know.com/academics/heronian-triangles-generator-calculator.html Heronian triangles]'''
are triangles whose sides ''and area'' are all integers.
: An example is the triangle with sides &nbsp; '''3, 4, 5''' &nbsp; whose area is &nbsp; '''6''' &nbsp; (and whose perimeter is &nbsp; '''12''').
 
<br>
Note that any triangle whose sides are all an integer multiple of 3,4,5; such as 6,8,10, will
Note that any triangle whose sides are all an integer multiple of &nbsp; '''3, 4, 5'''; &nbsp; such as &nbsp; '''6, 8, 10,''' &nbsp; will also be a Heronian triangle.
also be a Heronian triangle.
 
Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor
of all three sides is &nbsp; '''1.''' This&nbsp; will exclude, for example triangle(unity). 6,8,10
 
This will exclude, for example, triangle &nbsp; '''6, 8, 10.'''
'''The task''' is to:
 
 
;Task:
# Create a named function/method/procedure/... that implements Hero's formula.
# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.
Line 26 ⟶ 30:
# Show the first ten ordered triangles in a table of sides, perimeter, and area.
# Show a similar ordered table for those triangles with area = 210
 
<br>
Show all output here.
 
<small>'''Note''': when generating triangles it may help to restrict</small> <math>a <= b <= c</math></small>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F gcd(=u, =v)
L v != 0
(u, v) = (v, u % v)
R abs(u)
 
F hero(a, b, c)
V s = (a + b + c) / 2
V a2 = s * (s - a) * (s - b) * (s - c)
R I a2 > 0 {sqrt(a2)} E 0
 
F is_heronian(a, b, c)
V x = hero(a, b, c)
R x > 0 & fract(x) == 0
 
F gcd3(x, y, z)
R gcd(gcd(x, y), z)
 
V MAXSIDE = 200
[(Int, Int, Int)] h
L(x) 1..MAXSIDE
L(y) x..MAXSIDE
L(z) y..MAXSIDE
I (x + y > z) & gcd3(x, y, z) == 1 & is_heronian(x, y, z)
h [+]= (x, y, z)
 
h = sorted(h, key' x -> (hero(x[0], x[1], x[2]), sum(x), (x[2], x[1], x[0])))
 
print(‘Primitive Heronian triangles with sides up to #.: #.’.format(MAXSIDE, h.len))
print("\nFirst ten when ordered by increasing area, then perimeter, then maximum sides:")
print(h[0.<10].map3((x, y, z) -> ‘ #14 perim: #3 area: #.’.format(String((x, y, z)), x + y + z, hero(x, y, z))).join("\n"))
print("\nAll with area 210 subject to the previous ordering:")
print(h.filter3((x, y, z) -> hero(x, y, z) == 210).map3((x, y, z) -> ‘ #14 perim: #3 area: #.’.format(String((x, y, z)), x + y + z, hero(x, y, z))).join("\n"))</syntaxhighlight>
 
{{out}}
<pre>
Primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter, then maximum sides:
(3, 4, 5) perim: 12 area: 6
(5, 5, 6) perim: 16 area: 12
(5, 5, 8) perim: 18 area: 12
(4, 13, 15) perim: 32 area: 24
(5, 12, 13) perim: 30 area: 30
(9, 10, 17) perim: 36 area: 36
(3, 25, 26) perim: 54 area: 36
(7, 15, 20) perim: 42 area: 42
(10, 13, 13) perim: 36 area: 60
(8, 15, 17) perim: 40 area: 60
 
All with area 210 subject to the previous ordering:
(17, 25, 28) perim: 70 area: 210
(20, 21, 29) perim: 70 area: 210
(12, 35, 37) perim: 84 area: 210
(17, 28, 39) perim: 84 area: 210
(7, 65, 68) perim: 140 area: 210
(3, 148, 149) perim: 300 area: 210
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Containers.Indefinite_Ordered_Sets;
with Ada.Finalization;
with Ada.Text_IO; use Ada.Text_IO;
procedure Heronian is
package Int_IO is new Ada.Text_IO.Integer_IO(Integer);
use Int_IO;
-- ----- Some math...
function GCD (A, B : in Natural) return Natural is (if B = 0 then A else GCD (B, A mod B));
function Int_Sqrt (N : in Natural) return Natural is
R1 : Natural := N;
R2 : Natural;
begin
if N <= 1 then
return N;
end if;
loop
R2 := (R1+N/R1)/2;
if R2 >= R1 then
return R1;
end if;
R1 := R2;
end loop;
end Int_Sqrt;
-- ----- Defines the triangle with sides as discriminants and a constructor which will
-- compute its other characteristics
type t_Triangle (A, B, C : Positive) is new Ada.Finalization.Controlled with record
Is_Heronian : Boolean;
Perimeter : Positive;
Area : Natural;
end record;
 
overriding procedure Initialize (Self : in out t_Triangle) is
-- Let's stick to integer computations, therefore a modified hero's formula
-- will be used : S*(S-a)*(S-b)*(S-c) = (a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c)/16
-- This will require long integers because at max side size, the product
-- before /16 excesses 2^31
Long_Product : Long_Long_Integer;
Short_Product : Natural;
begin
Self.Perimeter := Self.A + Self.B + Self.C;
Long_Product := Long_Long_Integer(Self.Perimeter)
* Long_Long_Integer(- Self.A + Self.B + Self.C)
* Long_Long_Integer( Self.A - Self.B + Self.C)
* Long_Long_Integer( Self.A + Self.B - Self.C);
Short_Product := Natural(Long_Product / 16);
Self.Area := Int_Sqrt (Short_Product);
Self.Is_Heronian := (Long_Product mod 16 = 0) and (Self.Area * Self.Area = Short_Product);
end Initialize;
-- ----- Ordering triangles with criteria (Area,Perimeter,A,B,C)
function "<" (Left, Right : in t_Triangle) return Boolean is
(Left.Area < Right.Area or else (Left.Area = Right.Area and then
(Left.Perimeter < Right.Perimeter or else (Left.Perimeter = Right.Perimeter and then
(Left.A < Right.A or else (Left.A = Right.A and then
(Left.B < Right.B or else (Left.B = Right.B and then
Left.C < Right.C))))))));
package Triangle_Lists is new Ada.Containers.Indefinite_Ordered_Sets (t_Triangle);
use Triangle_Lists;
 
-- ----- Displaying triangle characteristics
Header : constant String := " A B C Per Area" & ASCII.LF & "---+---+---+---+-----";
procedure Put_Triangle (Position : Cursor) is
Triangle : constant t_Triangle := Element(Position);
begin
Put(Triangle.A, 3);
Put(Triangle.B, 4);
Put(Triangle.C, 4);
Put(Triangle.Perimeter, 4);
Put(Triangle.Area, 6);
New_Line;
end Put_Triangle;
 
-- ----- Global variables
Triangles : Set := Empty_Set;
-- Instead of constructing two sets, or browsing all the beginning of the set during
-- the second output, start/end cursors will be updated during the insertions.
First_201 : Cursor := No_Element;
Last_201 : Cursor := No_Element;
 
procedure Memorize_Triangle (A, B, C : in Positive) is
Candidate : t_Triangle(A, B, C);
Position : Cursor;
Dummy : Boolean;
begin
if Candidate.Is_Heronian then
Triangles.Insert (Candidate, Position, Dummy);
if Candidate.Area = 210 then
First_201 := (if First_201 = No_Element then Position
elsif Position < First_201 then Position
else First_201);
Last_201 := (if Last_201 = No_Element then Position
elsif Last_201 < Position then Position
else Last_201);
end if;
end if;
end Memorize_Triangle;
begin
-- Loops restrict to unique A,B,C (ensured by A <= B <= C) with sides < 200 and for
-- which a triangle is constructible : C is not greater than B+A (flat triangle)
for A in 1..200 loop
for B in A..200 loop
for C in B..Integer'Min(A+B-1,200) loop
-- Filter non-primitive triangles
if GCD(GCD(A,B),C) = 1 then
Memorize_Triangle (A, B, C);
end if;
end loop;
end loop;
end loop;
Put_Line (Triangles.Length'Img & " heronian triangles found :");
Put_Line (Header);
Triangles.Iterate (Process => Put_Triangle'Access);
New_Line;
Put_Line ("Heronian triangles with area = 201");
Put_Line (Header);
declare
Position : Cursor := First_201;
begin
loop
Put_Triangle (Position);
exit when Position = Last_201;
Position := Next(Position);
end loop;
end;
end Heronian;</syntaxhighlight>
{{out}}
<pre> 517 heronian triangles found :
A B C Per Area
---+---+---+---+-----
3 4 5 12 6
5 5 6 16 12
5 5 8 18 12
4 13 15 32 24
5 12 13 30 30
9 10 17 36 36
3 25 26 54 36
7 15 20 42 42
10 13 13 36 60
8 15 17 40 60</pre>
...
<pre>
Heronian triangles with area = 201
A B C Per Area
---+---+---+---+-----
17 25 28 70 210
20 21 29 70 210
12 35 37 84 210
17 28 39 84 210
7 65 68 140 210
3 148 149 300 210</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Lua}}
<syntaxhighlight lang="algol68"># mode to hold details of a Heronian triangle #
MODE HERONIAN = STRUCT( INT a, b, c, area, perimeter );
# returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one #
PROC try ht = ( INT a, b, c )REF HERONIAN:
BEGIN
REF HERONIAN t := NIL;
REAL s = ( a + b + c ) / 2;
REAL area squared = s * ( s - a ) * ( s - b ) * ( s - c );
IF area squared > 0 THEN
# a, b, c does form a triangle #
REAL area = sqrt( area squared );
IF ENTIER area = area THEN
# the area is integral so the triangle is Heronian #
t := HEAP HERONIAN := ( a, b, c, ENTIER area, a + b + c )
FI
FI;
t
END # try ht # ;
# returns the GCD of a and b #
PROC gcd = ( INT a, b )INT: IF b = 0 THEN a ELSE gcd( b, a MOD b ) FI;
# prints the details of the Heronian triangle t #
PROC ht print = ( REF HERONIAN t )VOID:
print( ( whole( a OF t, -4 ), whole( b OF t, -5 ), whole( c OF t, -5 ), whole( area OF t, -5 ), whole( perimeter OF t, -10 ), newline ) );
# prints headings for the Heronian Triangle table #
PROC ht title = VOID: print( ( " a b c area perimeter", newline, "---- ---- ---- ---- ---------", newline ) );
 
BEGIN
# construct ht as a table of the Heronian Triangles with sides up to 200 #
[ 1 : 1000 ]REF HERONIAN ht;
REF HERONIAN t;
INT ht count := 0;
 
FOR c TO 200 DO
FOR b TO c DO
FOR a TO b DO
IF gcd( gcd( a, b ), c ) = 1 THEN
t := try ht( a, b, c );
IF REF HERONIAN(t) ISNT REF HERONIAN(NIL) THEN
ht[ ht count +:= 1 ] := t
FI
FI
OD
OD
OD;
 
# sort the table on ascending area, perimeter and max side length #
# note we constructed the triangles with c as the longest side #
BEGIN
INT lower := 1, upper := ht count;
WHILE upper := upper - 1;
BOOL swapped := FALSE;
FOR i FROM lower TO upper DO
REF HERONIAN h := ht[ i ];
REF HERONIAN k := ht[ i + 1 ];
IF area OF k < area OF h OR ( area OF k = area OF h
AND ( perimeter OF k < perimeter OF h
OR ( perimeter OF k = perimeter OF h
AND c OF k < c OF h
)
)
)
THEN
ht[ i ] := k;
ht[ i + 1 ] := h;
swapped := TRUE
FI
OD;
swapped
DO SKIP OD;
 
# display the triangles #
print( ( "There are ", whole( ht count, 0 ), " Heronian triangles with sides up to 200", newline ) );
ht title;
FOR ht pos TO 10 DO ht print( ht( ht pos ) ) OD;
print( ( " ...", newline ) );
print( ( "Heronian triangles with area 210:", newline ) );
ht title;
FOR ht pos TO ht count DO
REF HERONIAN t := ht[ ht pos ];
IF area OF t = 210 THEN ht print( t ) FI
OD
END
END</syntaxhighlight>
{{out}}
<pre>
There are 517 Heronian triangles with sides up to 200
a b c area perimeter
---- ---- ---- ---- ---------
3 4 5 6 12
5 5 6 12 16
5 5 8 12 18
4 13 15 24 32
5 12 13 30 30
9 10 17 36 36
3 25 26 36 54
7 15 20 42 42
10 13 13 60 36
8 15 17 60 40
...
Heronian triangles with area 210:
a b c area perimeter
---- ---- ---- ---- ---------
17 25 28 210 70
20 21 29 210 70
12 35 37 210 84
17 28 39 210 84
7 65 68 210 140
3 148 149 210 300
</pre>
 
=={{header|ALGOL W}}==
{{Trans|Lua}}
<syntaxhighlight lang="algolw">begin
% record to hold details of a Heronian triangle %
record Heronian ( integer a, b, c, area, perimeter );
% returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one %
reference(Heronian) procedure tryHt( integer value a, b, c ) ;
begin
real s, areaSquared, area;
reference(Heronian) t;
s := ( a + b + c ) / 2;
areaSquared := s * ( s - a ) * ( s - b ) * ( s - c );
t := null;
if areaSquared > 0 then begin
% a, b, c does form a triangle %
area := sqrt( areaSquared );
if entier( area ) = area then begin
% the area is integral so the triangle is Heronian %
t := Heronian( a, b, c, entier( area ), a + b + c )
end
end;
t
end tryHt ;
 
% returns the GCD of a and b %
integer procedure gcd( integer value a, b ) ; if b = 0 then a else gcd( b, a rem b );
 
% prints the details of the Heronian triangle t %
procedure htPrint( reference(Heronian) value t ) ; write( i_w := 4, s_w := 1, a(t), b(t), c(t), area(t), " ", perimeter(t) );
% prints headings for the Heronian Triangle table %
procedure htTitle ; begin write( " a b c area perimeter" ); write( "---- ---- ---- ---- ---------" ) end;
 
begin
% construct ht as a table of the Heronian Triangles with sides up to 200 %
reference(Heronian) array ht ( 1 :: 1000 );
reference(Heronian) t;
integer htCount;
 
htCount := 0;
for c := 1 until 200 do begin
for b := 1 until c do begin
for a := 1 until b do begin
if gcd( gcd( a, b ), c ) = 1 then begin
t := tryHt( a, b, c );
if t not = null then begin
htCount := htCount + 1;
ht( htCount ) := t
end
end
end
end
end;
 
% sort the table on ascending area, perimeter and max side length %
% note we constructed the triangles with c as the longest side %
begin
integer lower, upper;
reference(Heronian) k, h;
logical swapped;
lower := 1;
upper := htCount;
while begin
upper := upper - 1;
swapped := false;
for i := lower until upper do begin
h := ht( i );
k := ht( i + 1 );
if area(k) < area(h) or ( area(k) = area(h)
and ( perimeter(k) < perimeter(h)
or ( perimeter(k) = perimeter(h)
and c(k) < c(h)
)
)
)
then begin
ht( i ) := k;
ht( i + 1 ) := h;
swapped := true;
end
end;
swapped
end
do begin end;
end;
 
% display the triangles %
write( "There are ", htCount, " Heronian triangles with sides up to 200" );
htTitle;
for htPos := 1 until 10 do htPrint( ht( htPos ) );
write( " ..." );
write( "Heronian triangles with area 210:" );
htTitle;
for htPos := 1 until htCount do begin
reference(Heronian) t;
t := ht( htPos );
if area(t) = 210 then htPrint( t )
end
end
end.</syntaxhighlight>
{{out}}
<pre>
There are 517 Heronian triangles with sides up to 200
a b c area perimeter
---- ---- ---- ---- ---------
3 4 5 6 12
5 5 6 12 16
5 5 8 12 18
4 13 15 24 32
5 12 13 30 30
9 10 17 36 36
3 25 26 36 54
7 15 20 42 42
10 13 13 60 36
8 15 17 60 40
...
Heronian triangles with area 210:
a b c area perimeter
---- ---- ---- ---- ---------
17 25 28 210 70
20 21 29 210 70
12 35 37 210 84
17 28 39 210 84
7 65 68 210 140
3 148 149 210 300
</pre>
 
=={{header|AppleScript}}==
 
By composition of functional primitives, and using post-Yosemite AppleScript's ability to import Foundation classes (mainly for sorting records, here).
 
{{Trans|JavaScript}}
<syntaxhighlight lang="applescript">use framework "Foundation"
 
-- HERONIAN TRIANGLES --------------------------------------------------------
 
-- heroniansOfSideUpTo :: Int -> [(Int, Int, Int)]
on heroniansOfSideUpTo(n)
script sideA
on |λ|(a)
script sideB
on |λ|(b)
script sideC
-- primitiveHeronian :: Int -> Int -> Int -> Bool
on primitiveHeronian(x, y, z)
(x ≤ y and y ≤ z) and (x + y > z) and ¬
gcd(gcd(x, y), z) = 1 and ¬
isIntegerValue(hArea(x, y, z))
end primitiveHeronian
on |λ|(c)
if primitiveHeronian(a, b, c) then
{{a, b, c}}
else
{}
end if
end |λ|
end script
concatMap(sideC, enumFromTo(b, n))
end |λ|
end script
concatMap(sideB, enumFromTo(a, n))
end |λ|
end script
concatMap(sideA, enumFromTo(1, n))
end heroniansOfSideUpTo
 
 
-- TEST ----------------------------------------------------------------------
on run
set n to 200
set lstHeron to ¬
sortByComparing({{"area", true}, {"perimeter", true}, {"maxSide", true}}, ¬
map(triangleDimensions, heroniansOfSideUpTo(n)))
set lstCols to {"sides", "perimeter", "area"}
set lstColWidths to {20, 15, 0}
set area to 210
script areaFilter
-- Record -> [Record]
on |λ|(recTriangle)
if area of recTriangle = area then
{recTriangle}
else
{}
end if
end |λ|
end script
intercalate("\n \n", {("Number of triangles found (with sides <= 200): " & ¬
length of lstHeron as string), ¬
¬
tabulation("First 10, ordered by area, perimeter, longest side", ¬
items 1 thru 10 of lstHeron, lstCols, lstColWidths), ¬
¬
tabulation("Area = 210", ¬
concatMap(areaFilter, lstHeron), lstCols, lstColWidths)})
end run
 
-- triangleDimensions :: (Int, Int, Int) ->
-- {sides: (Int, Int, Int), area: Int, perimeter: Int, maxSize: Int}
on triangleDimensions(lstSides)
set {x, y, z} to lstSides
{sides:[x, y, z], area:hArea(x, y, z) as integer, perimeter:x + y + z, maxSide:z}
end triangleDimensions
 
-- hArea :: Int -> Int -> Int -> Num
on hArea(x, y, z)
set s to (x + y + z) / 2
set a to s * (s - x) * (s - y) * (s - z)
if a > 0 then
a ^ 0.5
else
0
end if
end hArea
 
-- gcd :: Int -> Int -> Int
on gcd(m, n)
if n = 0 then
m
else
gcd(n, m mod n)
end if
end gcd
 
 
-- TABULATION ----------------------------------------------------------------
 
-- tabulation :: [Record] -> [String] -> String -> [Integer] -> String
on tabulation(strLegend, lstRecords, lstKeys, lstWidths)
script heading
on |λ|(strTitle, iCol)
set str to toTitle(strTitle)
str & replicate((item iCol of lstWidths) - (length of str), space)
end |λ|
end script
script lineString
on |λ|(rec)
script fieldString
-- fieldString :: String -> Int -> String
on |λ|(strKey, i)
set v to keyValue(strKey, rec)
if class of v is list then
set strData to ("(" & intercalate(", ", v) & ")")
else
set strData to v as string
end if
strData & replicate(space, (item i of (lstWidths)) - (length of strData))
end |λ|
end script
tab & intercalate(tab, map(fieldString, lstKeys))
end |λ|
end script
strLegend & ":" & linefeed & linefeed & ¬
tab & intercalate(tab, ¬
map(heading, lstKeys)) & linefeed & ¬
intercalate(linefeed, map(lineString, lstRecords))
end tabulation
 
-- GENERIC FUNCTIONS ---------------------------------------------------------
 
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
 
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
concat(map(f, xs))
end concatMap
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
 
-- isIntegerValue :: Num -> Bool
on isIntegerValue(n)
{real, integer} contains class of n and (n = (n as integer))
end isIntegerValue
 
-- keyValue :: String -> Record -> Maybe String
on keyValue(strKey, rec)
set ca to current application
set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey
if v is not missing value then
item 1 of ((ca's NSArray's arrayWithObject:v) as list)
else
missing value
end if
end keyValue
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
-- replicate :: Int -> String -> String
on replicate(n, s)
set out to ""
if n < 1 then return out
set dbl to s
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
 
-- List of {strKey, blnAscending} pairs -> list of records -> sorted list of records
 
-- sortByComparing :: [(String, Bool)] -> [Records] -> [Records]
on sortByComparing(keyDirections, xs)
set ca to current application
script recDict
on |λ|(x)
ca's NSDictionary's dictionaryWithDictionary:x
end |λ|
end script
set dcts to map(recDict, xs)
script asDescriptor
on |λ|(kd)
set {k, d} to kd
ca's NSSortDescriptor's sortDescriptorWithKey:k ascending:d selector:dcts
end |λ|
end script
((ca's NSArray's arrayWithArray:dcts)'s ¬
sortedArrayUsingDescriptors:map(asDescriptor, keyDirections)) as list
end sortByComparing
 
-- toTitle :: String -> String
on toTitle(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toTitle</syntaxhighlight>
{{Out}}
<pre>Number of triangles found (with sides <= 200): 517
 
First 10, ordered by area, perimeter, longest side:
 
Sides Perimeter Area
(3, 4, 5) 12 6
(5, 5, 6) 16 12
(5, 5, 8) 18 12
(4, 13, 15) 32 24
(5, 12, 13) 30 30
(9, 10, 17) 36 36
(3, 25, 26) 54 36
(7, 15, 20) 42 42
(10, 13, 13) 36 60
(8, 15, 17) 40 60
 
Area = 210:
 
Sides Perimeter Area
(17, 25, 28) 70 210
(20, 21, 29) 70 210
(12, 35, 37) 84 210
(17, 28, 39) 84 210
(7, 65, 68) 140 210
(3, 148, 149) 300 210</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">printTable: function [title, rows][
print title ++ ":"
print repeat "=" 60
 
prints pad.center "A" 10
prints pad.center "B" 10
prints pad.center "C" 10
prints pad.center "Perimeter" 15
print pad.center "Area" 15
print repeat "-" 60
 
loop rows 'row [
prints pad.center to :string row\0 10
prints pad.center to :string row\1 10
prints pad.center to :string row\2 10
prints pad.center to :string row\3 15
print pad.center to :string row\4 15
]
print ""
]
 
hero: function [a,b,c][
s: (a + b + c) // 2
return sqrt(s * (s-a) * (s-b) * (s-c))
]
 
heronian?: function [x]->
and? -> x > 0
-> x = ceil x
 
lst: []
mx: 200
 
loop 1..mx 'c ->
loop 1..c 'b ->
loop 1..b 'a [
area: hero a b c
if and? [heronian? area] [one? gcd @[a b c]]->
'lst ++ @[
@[a, b, c, a + b + c, to :integer area]
]
]
 
print ["Number of Heronian triangles:" size lst]
print ""
 
lst: arrange lst 'item ->
(item\4 * 10000) + (item\3 * 100) + max first.n:3 item
 
printTable "Ordered list of first ten Heronian triangles" first.n: 10 lst
printTable "Ordered list of Heronian triangles with area 210" select lst 'x -> x\4 = 210</syntaxhighlight>
 
{{out}}
 
<pre>Number of Heronian triangles: 517
 
Ordered list of first ten Heronian triangles:
============================================================
A B C Perimeter Area
------------------------------------------------------------
3 4 5 12 6
5 5 6 16 12
5 5 8 18 12
4 13 15 32 24
5 12 13 30 30
9 10 17 36 36
3 25 26 54 36
7 15 20 42 42
10 13 13 36 60
8 15 17 40 60
 
Ordered list of Heronian triangles with area 210:
============================================================
A B C Perimeter Area
------------------------------------------------------------
17 25 28 70 210
20 21 29 70 210
12 35 37 84 210
17 28 39 84 210
7 65 68 140 210
3 148 149 300 210</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Primitive_Heronian_triangles(MaxSide){
obj :=[]
loop, % MaxSide {
Line 49 ⟶ 904:
x := StrSplit(x, "`t"), y := StrSplit(y, "`t")
return x.1 > y.1 ? 1 : x.1 < y.1 ? -1 : x.2 > y.2 ? 1 : x.2 < y.2 ? -1 : 0
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">res := Primitive_Heronian_triangles(200)
loop, parse, res, `n, `r
{
Line 65 ⟶ 920:
. "`nResults for Area = 210:"
. "`n" "Area`tPerimeter`tSides`n" res3
return</langsyntaxhighlight>
Outputs:<pre>517 results found
 
Line 90 ⟶ 945:
210 300 3, 148, 149</pre>
 
=={{header|C++}}==
Takes max side, number of triangles to print and area limit as inputs. Area should be -1 if it is not a restriction. Triangles are stored in a linked list which is built sorted and hence no post processing is required. Usage is printed out on incorrect invocation.
{{Works with|C++11}}
<lang cpp>#include <algorithm>
#include <cmath>
#include <iostream>
#include <tuple>
#include <vector>
 
----
int gcd(int a, int b)
'''IMPORTANT''': This is a C99 compatible implementation. May result in errors on earlier compilers.
{
<syntaxhighlight lang="c">
int rem = 1, dividend, divisor;
#include<stdlib.h>
std::tie(divisor, dividend) = std::minmax(a, b);
#include<stdio.h>
while (rem != 0) {
#include<math.h>
rem = dividend % divisor;
if (rem != 0) {
dividend = divisor;
divisor = rem;
}
}
return divisor;
}
 
typedef struct{
struct Triangle
int a,b,c;
{
int aperimeter;
double area;
int b;
}triangle;
int c;
};
 
typedef struct elem{
int perimeter(const Triangle& triangle)
triangle t;
{
struct elem* next;
return triangle.a + triangle.b + triangle.c;
}cell;
 
typedef cell* list;
 
void addAndOrderList(list *a,triangle t){
list iter,temp;
int flag = 0;
if(*a==NULL){
*a = (list)malloc(sizeof(cell));
(*a)->t = t;
(*a)->next = NULL;
}
else{
temp = (list)malloc(sizeof(cell));
 
iter = *a;
while(iter->next!=NULL){
if(((iter->t.area<t.area)||(iter->t.area==t.area && iter->t.perimeter<t.perimeter)||(iter->t.area==t.area && iter->t.perimeter==t.perimeter && iter->t.a<=t.a))
&&
(iter->next==NULL||(t.area<iter->next->t.area || t.perimeter<iter->next->t.perimeter || t.a<iter->next->t.a))){
temp->t = t;
temp->next = iter->next;
iter->next = temp;
flag = 1;
break;
}
 
iter = iter->next;
}
if(flag!=1){
temp->t = t;
temp->next = NULL;
iter->next = temp;
}
}
}
 
int gcd(int a,int b){
double area(const Triangle& t)
if(b!=0)
{
return gcd(b,a%b);
double p_2 = perimeter(t) / 2.;
return a;
double area_sq = p_2 * ( p_2 - t.a ) * ( p_2 - t.b ) * ( p_2 - t.c );
return sqrt(area_sq);
}
 
void calculateArea(triangle *t){
std::vector<Triangle> generate_triangles(int side_limit = 200)
(*t).perimeter = (*t).a + (*t).b + (*t).c;
{
(*t).area = sqrt(0.5*(*t).perimeter*(0.5*(*t).perimeter - (*t).a)*(0.5*(*t).perimeter - (*t).b)*(0.5*(*t).perimeter - (*t).c));
std::vector<Triangle> result;
for(int a = 1; a <= side_limit; ++a)
for(int b = 1; b <= a; ++b)
for(int c = a+1-b; c <= b; ++c) // skip too-small values of c, which will violate triangle inequality
{
Triangle t{a, b, c};
double t_area = area(t);
if(t_area == 0) continue;
if( std::floor(t_area) == std::ceil(t_area) && gcd(a, gcd(b, c)) == 1)
result.push_back(t);
}
return result;
}
 
list generateTriangleList(int maxSide,int *count){
bool compare(const Triangle& lhs, const Triangle& rhs)
int a,b,c;
{
triangle t;
return std::make_tuple(area(lhs), perimeter(lhs), std::max(lhs.a, std::max(lhs.b, lhs.c))) <
list herons = NULL;
std::make_tuple(area(rhs), perimeter(rhs), std::max(rhs.a, std::max(rhs.b, rhs.c)));
*count = 0;
for(a=1;a<=maxSide;a++){
for(b=1;b<=a;b++){
for(c=1;c<=b;c++){
if(c+b > a && gcd(gcd(a,b),c)==1){
t = (triangle){a,b,c};
calculateArea(&t);
if(t.area/(int)t.area == 1){
addAndOrderList(&herons,t);
(*count)++;
}
}
}
}
}
return herons;
}
 
void printList(list a,int limit,int area){
struct area_compare
list iter = a;
{
int count = 1;
bool operator()(const Triangle& t, int i) { return area(t) < i; }
bool operator()(int i, const Triangle& t) { return i < area(t); }
printf("\nDimensions\tPerimeter\tArea");
};
while(iter!=NULL && count!=limit+1){
if(area==-1 ||(area==iter->t.area)){
printf("\n%d x %d x %d\t%d\t\t%d",iter->t.a,iter->t.b,iter->t.c,iter->t.perimeter,(int)iter->t.area);
count++;
}
iter = iter->next;
}
}
 
int main(int argC,char* argV[])
{
int count;
auto tri = generate_triangles();
list herons = NULL;
std::cout << "There are " << tri.size() << " primitive Heronian triangles with sides up to 200\n\n";
 
if(argC!=4)
std::cout << "First ten when ordered by increasing area, then perimeter, then maximum sides:\n";
printf("Usage : %s <Max side, max triangles to print and area, -1 for area to ignore>",argV[0]);
std::sort(tri.begin(), tri.end(), compare);
else{
std::cout << "area\tperimeter\tsides\n";
herons = generateTriangleList(atoi(argV[1]),&count);
for(int i = 0; i < 10; ++i)
printf("Triangles found : %d",count);
std::cout << area(tri[i]) << '\t' << perimeter(tri[i]) << "\t\t" <<
(atoi(argV[3])==-1)?printf("\nPrinting first %s triangles.",argV[2]):printf("\nPrinting triangles with area %s square units.",argV[3]);
tri[i].a << 'x' << tri[i].b << 'x' << tri[i].c << '\n';
printList(herons,atoi(argV[2]),atoi(argV[3]));
 
free(herons);
std::cout << "\nAll with area 210 subject to the previous ordering:\n";
}
auto range = std::equal_range(tri.begin(), tri.end(), 210, area_compare());
return 0;
std::cout << "area\tperimeter\tsides\n";
for(auto it = range.first; it != range.second; ++it)
std::cout << area(*it) << '\t' << perimeter(*it) << "\t\t" <<
it->a << 'x' << it->b << 'x' << it->c << '\n';
}
</syntaxhighlight>
</lang>
Invocation and output :
{{out}}
<pre>
<lang>There are 517 primitive Heronian triangles with sides up to 200
C:\rosettaCode>heronian.exe 200 10 -1
 
Triangles found : 517
First ten when ordered by increasing area, then perimeter, then maximum sides:
Printing first 10 triangles.
area perimeter sides
6Dimensions Perimeter 12 5x4x3Area
125 x 4 x 3 16 12 6x5x56
126 x 5 x 5 18 16 8x5x5 12
248 x 5 x 5 32 18 15x13x4 12
3015 x 13 x 4 30 32 13x12x5 24
3613 x 12 x 5 36 30 17x10x9 30
3617 x 10 x 9 54 36 26x25x3 36
4226 x 25 x 3 42 54 20x15x7 36
6020 x 15 x 7 36 42 13x13x10 42
6013 x 13 x 10 40 36 17x15x8 60
17 x 15 x 8 40 60
 
C:\rosettaCode>heronian.exe 200 10 210
All with area 210 subject to the previous ordering:
Triangles found : 517
area perimeter sides
Printing triangles with area 210 square units.
210 70 28x25x17
210Dimensions 70 Perimeter 29x21x20Area
21028 x 25 x 17 84 70 37x35x12 210
21029 x 21 x 20 84 70 39x28x17 210
21037 x 35 x 12 140 84 68x65x7 210
21039 x 28 x 17 300 84 149x148x3 210
68 x 65 x 7 140 210
</lang>
149 x 148 x 3 300 210
</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
<lang Csharp>
using System;
using System.Collections.Generic;
 
Line 264 ⟶ 1,158:
}
}
}</syntaxhighlight>
}
</lang>
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
<lang>
Number of primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter,then maximum sides:
Line 290 ⟶ 1,182:
17 28 39 84 210
7 65 68 140 210
3 148 149 300 210</pre>
 
</lang>
=={{header|C++}}==
{{Works with|C++17}}
<syntaxhighlight lang="cpp">#include <tuple>
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>
 
#include <cmath>
 
struct Triangle {
int a{};
int b{};
int c{};
 
[[nodiscard]] constexpr auto perimeter() const noexcept { return a + b + c; }
 
[[nodiscard]] constexpr auto area() const noexcept {
const auto p_2 = static_cast<double>(perimeter()) / 2;
const auto area_sq = p_2 * (p_2 - a) * (p_2 - b) * (p_2 - c);
return std::sqrt(area_sq);
}
};
 
 
auto generate_triangles(int side_limit = 200) {
std::vector<Triangle> result;
for(int a = 1; a <= side_limit; ++a)
for(int b = 1; b <= a; ++b)
for(int c = a + 1 - b; c <= b; ++c) // skip too-small values of c, which will violate triangle inequality
{
Triangle t{ a, b, c };
const auto t_area = t.area();
if (t_area == 0) continue;
if (std::floor(t_area) == std::ceil(t_area) && std::gcd(a, std::gcd(b, c)) == 1)
result.push_back(t);
}
return result;
}
 
bool compare(const Triangle& lhs, const Triangle& rhs) noexcept {
return std::make_tuple(lhs.area(), lhs.perimeter(), std::max(lhs.a, std::max(lhs.b, lhs.c))) <
std::make_tuple(rhs.area(), rhs.perimeter(), std::max(rhs.a, std::max(rhs.b, rhs.c)));
}
 
struct area_compare {
[[nodiscard]] constexpr bool operator()(const Triangle& t, int i) const noexcept { return t.area() < i; }
[[nodiscard]] constexpr bool operator()(int i, const Triangle& t) const noexcept { return i < t.area(); }
};
 
int main() {
auto tri = generate_triangles();
std::cout << "There are " << tri.size() << " primitive Heronian triangles with sides up to 200\n\n";
 
std::cout << "First ten when ordered by increasing area, then perimeter, then maximum sides:\n";
std::sort(tri.begin(), tri.end(), compare);
std::cout << "area\tperimeter\tsides\n";
for(int i = 0; i < 10; ++i)
std::cout << tri[i].area() << '\t' << tri[i].perimeter() << "\t\t" <<
tri[i].a << 'x' << tri[i].b << 'x' << tri[i].c << '\n';
 
std::cout << "\nAll with area 210 subject to the previous ordering:\n";
auto range = std::equal_range(tri.begin(), tri.end(), 210, area_compare());
std::cout << "area\tperimeter\tsides\n";
for(auto it = range.first; it != range.second; ++it)
std::cout << (*it).area() << '\t' << (*it).perimeter() << "\t\t" <<
it->a << 'x' << it->b << 'x' << it->c << '\n';
}</syntaxhighlight>
{{out}}
<pre>There are 517 primitive Heronian triangles with sides up to 200
 
First ten when ordered by increasing area, then perimeter, then maximum sides:
area perimeter sides
6 12 5x4x3
12 16 6x5x5
12 18 8x5x5
24 32 15x13x4
30 30 13x12x5
36 36 17x10x9
36 54 26x25x3
42 42 20x15x7
60 36 13x13x10
60 40 17x15x8
 
All with area 210 subject to the previous ordering:
area perimeter sides
210 70 28x25x17
210 70 29x21x20
210 84 37x35x12
210 84 39x28x17
210 140 68x65x7
210 300 149x148x3</pre>
 
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<syntaxhighlight lang="coffeescript">heronArea = (a, b, c) ->
s = (a + b + c) / 2
Math.sqrt s * (s - a) * (s - b) * (s - c)
 
isHeron = (h) -> h % 1 == 0 and h > 0
 
gcd = (a, b) ->
leftover = 1
dividend = if a > b then a else b
divisor = if a > b then b else a
until leftover == 0
leftover = dividend % divisor
if leftover > 0
dividend = divisor
divisor = leftover
divisor
 
list = []
for c in [1..200]
for b in [1..c]
for a in [1..b]
area = heronArea(a, b, c)
if gcd(gcd(a, b), c) == 1 and isHeron(area)
list.push new Array(a, b, c, a + b + c, area)
 
sort = (list) ->
swapped = true
while swapped
swapped = false
for i in [1..list.length-1]
if list[i][4] < list[i - 1][4] or list[i][4] == list[i - 1][4] and list[i][3] < list[i - 1][3]
temp = list[i]
list[i] = list[i - 1]
list[i - 1] = temp
swapped = true
sort list
 
# some results:
console.log 'primitive Heronian triangles with sides up to 200: ' + list.length
console.log 'First ten when ordered by increasing area, then perimeter:'
for i in list[0..10-1]
console.log i[0..2].join(' x ') + ', p = ' + i[3] + ', a = ' + i[4]
 
console.log '\nHeronian triangles with area = 210:'
for i in list
if i[4] == 210
console.log i[0..2].join(' x ') + ', p = ' + i[3]</syntaxhighlight>
{{out}}
<pre>primitive Heronian triangles with sides up to 200: 517
First ten when ordered by increasing area, then perimeter:
3 x 4 x 5, p = 12, a = 6
5 x 5 x 6, p = 16, a = 12
5 x 5 x 8, p = 18, a = 12
4 x 13 x 15, p = 32, a = 24
5 x 12 x 13, p = 30, a = 30
9 x 10 x 17, p = 36, a = 36
3 x 25 x 26, p = 54, a = 36
7 x 15 x 20, p = 42, a = 42
10 x 13 x 13, p = 36, a = 60
8 x 15 x 17, p = 40, a = 60
 
Heronian triangles with area = 210:
17 x 25 x 28, p = 70
20 x 21 x 29, p = 70
12 x 35 x 37, p = 84
17 x 28 x 39, p = 84
7 x 65 x 68, p = 140
3 x 148 x 149, p = 300</pre>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.range, std.algorithm, std.numeric, std.traits, std.typecons;
 
double hero(in uint a, in uint b, in uint c) pure nothrow @safe @nogc {
Line 339 ⟶ 1,394:
"\nAll with area 210 subject to the previous ordering:".writeln;
showTriangles(h.filter!(t => t[].hero == 210));
}</langsyntaxhighlight>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 364 ⟶ 1,419:
210 140 7x65x68
210 300 3x148x149</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Heronian_triangles#Pascal Pascal].
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; returns quintuple (A s a b c)
;; or #f if not hero
Line 392 ⟶ 1,449:
(define (print-laurels H)
(writeln '🌿🌿 (length H) 'heroes '🌿🌿))
</syntaxhighlight>
</lang>
{{out}}
<pre>(define H (heroes))
(define H (heroes))
 
(print-laurels H)
Line 420 ⟶ 1,476:
A: 210 s: 84 sides: 39x28x17
A: 210 s: 140 sides: 68x65x7
A: 210 s: 300 sides: 149x148x3</pre>
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Heronian do
def triangle?(a,b,c) when a+b <= c, do: false
def triangle?(a,b,c) do
Line 459 ⟶ 1,514:
|> Enum.each(fn {a, b, c} ->
IO.puts "#{a}\t#{b}\t#{c}\t#{a+b+c}\t#{area_size}"
end)</langsyntaxhighlight>
 
{{out}}
<pre>517
517
 
Sides Perim Area
Line 482 ⟶ 1,536:
17 28 39 84 210
7 65 68 140 210
3 148 149 300 210</pre>
</pre>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM HERON
 
Line 554 ⟶ 1,607:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
<pre>Number of triangles: 517
<pre>
Number of triangles: 517
3 4 5 12 6
5 5 6 16 12
Line 573 ⟶ 1,625:
17 28 39 84 210
7 65 68 140 210
3 148 149 300 210</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: accessors assocs backtrack combinators.extras
combinators.short-circuit formatting io kernel locals math
math.functions math.order math.parser math.ranges mirrors qw
sequences sorting.slots ;
IN: rosetta-code.heronian-triangles
 
TUPLE: triangle a b c area perimeter ;
 
:: area ( a b c -- x )
a b + c + 2 / :> s
s s a - * s b - * s c - * sqrt ;
 
: <triangle> ( triplet-seq -- triangle )
[ first3 ] [ first3 area >integer ] [ sum ] tri
triangle boa ;
 
: heronian? ( a b c -- ? )
area dup [ complex? ] [ 0 number= ] bi or
[ drop f ] [ dup >integer number= ] if ;
: 3gcd ( a b c -- n ) [ gcd nip ] twice ;
: primitive-heronian? ( a b c -- ? )
{ [ 3gcd 1 = ] [ heronian? ] } 3&& ;
 
:: find-triangles ( -- seq )
[
200 [1,b] amb-lazy :> c ! Use backtrack vocab to test
c [1,b] amb-lazy :> b ! permutations of sides such
b [1,b] amb-lazy :> a ! that c >= b >= a.
a b c primitive-heronian? must-be-true
{ a b c } <triangle>
] bag-of ; ! collect every triangle
: sort-triangles ( seq -- seq' )
{ { area>> <=> } { perimeter>> <=> } } sort-by ;
CONSTANT: format "%4s%5s%5s%5s%10s\n"
: print-header ( -- )
qw{ a b c area perimeter } format vprintf
"---- ---- ---- ---- ---------" print ;
: print-triangle ( triangle -- )
<mirror> >alist values [ number>string ] map format vprintf ;
 
: print-triangles ( seq -- ) [ print-triangle ] each ; inline
: first10 ( sorted-triangles -- )
dup length "%d triangles found. First 10: \n" printf
print-header 10 head print-triangles ;
: area210= ( sorted-triangles -- )
"Triangles with area 210: " print print-header
[ area>> 210 = ] filter print-triangles ;
: main ( -- )
"Finding heronian triangles with sides <= 200..." print nl
find-triangles sort-triangles
[ first10 nl ] [ area210= ] bi ;
MAIN: main</syntaxhighlight>
{{out}}
<pre>
Finding heronian triangles with sides <= 200...
 
517 triangles found. First 10:
a b c area perimeter
---- ---- ---- ---- ---------
3 4 5 6 12
5 5 6 12 16
5 5 8 12 18
4 13 15 24 32
5 12 13 30 30
9 10 17 36 36
3 25 26 36 54
7 15 20 42 42
10 13 13 60 36
8 15 17 60 40
 
Triangles with area 210:
a b c area perimeter
---- ---- ---- ---- ---------
17 25 28 210 70
20 21 29 210 70
12 35 37 210 84
17 28 39 210 84
7 65 68 210 140
3 148 149 210 300
</pre>
 
=={{header|Fortran}}==
Earlier Fortran doesn't offer special functions such as SUM, PRODUCT and MAXVAL of arrays, nor the ability to create compound data aggregates such as STASH to store a triangle's details. Simple code would have to be used in the absence of such conveniences, and multiple ordinary arrays rather than an array of a compound data entity. Rather than attempt to create the candidate triangles in the desired order, the simple approach is to sort a list of triangles, and using an XNDX array evades tossing compound items about. Rather than create a procedure to do the sorting, a comb sort is not too much trouble to place in-line once. Further, since the ordering is based on a compound key, having only one comparison to code is a boon. The three-way-if statement is central to the expedient evaluation of a compound sort key, but this facility is deprecated by the modernists, with no alternative offered that avoids re-comparison of parts.
<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE GREEK MATHEMATICIANS !Two millenia back and more.
CONTAINS
Line 686 ⟶ 1,829:
END DO !Just thump through the lot.
END
</syntaxhighlight>
</lang>
 
{{out}}
Output:
<pre>517 triangles of integral area. Sides up to 200
<pre>
517 triangles of integral area. Sides up to 200
First 10, ordered by area, perimeter, longest side.
Index ---Sides--- Perimeter Area
Line 709 ⟶ 1,851:
36: 17 28 39 84 210
91: 7 65 68 140 210
329: 3 148 149 300 210</pre>
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 1502-0905-20152016
' compile with: fbc -s console
 
Line 745 ⟶ 1,886:
 
Function Heronian_triangles(a_max As UInteger, b_max As UInteger, _
c_max As UInteger, result() As triangle) As UInteger
 
Dim As UInteger a, b, c, c1
Dim As UInteger s, sqroot, total, temp
 
For a = 1 To a_max
For b = a To b_max
' make sure that a + b + c is even
For c = b + (a And 1) To c_max Step 2
' to form a triangle a + b must be greater then c
If (a + b) <= c Then Exit For
' check if a, b and c have a common divisor
If a > 1 And (gcd( ac, b) <> 1 And gcd(bc, ca) <> 1) Then Continue For
s = a + bContinue + cFor
'End at this point s needs to be evenIf
If (s And= 1)(a =+ 1b Then+ c) Continue\ For2
s \= 2 ' s = s \ 2
If c >= s Then Continue For
temp = s * (s - a) * (s - b) * (s - c)
sqroot = Sqr(temp)
If (sqroot * sqroot) = temp Then
total += 1
'Print a,b,c,s,sqroot
With result(total)
.a = a
Line 781 ⟶ 1,922:
End Function
 
' ------=< MAIN >=------
 
ReDimSub sort_tri(result(1 To 10000) As triangle, total As UInteger)
' shell sort
Dim As UInteger x, y, done, total, inc
' sort order: area, s, c
 
Dim As UInteger x, y, inc, done
total = Heronian_triangles(200, 200, 200, result() )
 
inc = total
' trim the array by removing empty entries
ReDim Preserve result(1 To total ) As triangle
 
' shell sort
' sort order area, s, c
inc = total
Do
inc = IIf(inc > 1, inc \ 2, 1)
Do
doneinc = 0IIf(inc > 1, inc \ 2, 1)
For x = 1 To total - incDo
ydone = x + inc0
IfFor result(x).area >= result(y).area1 ThenTo total - inc
Swapy = result(x), result(y)+ inc
doneIf =result(x).area 1> result(y).area Then
Else Swap result(x), result(y)
If result(x).area = result(y).area Thendone = 1
If result(x).s > result(y).s ThenElse
SwapIf result(x),.area = result(y).area Then
doneIf =result(x).s 1> result(y).s Then
Else Swap result(x), result(y)
If result(x).s = result(y).s Thendone = 1
If result(x).c > result(y).c ThenElse
SwapIf result(x),.s = result(y).s Then
doneIf =result(x).c 1> result(y).c Then
Swap result(x), result(y)
done = 1
End If
End If
End If
End If
End If
End IfNext
NextLoop Until done = 0
Loop Until doneinc = 01
 
Loop Until inc = 1
End Sub
 
 
' ------=< MAIN >=------
 
ReDim result(1 To 1000) As triangle
Dim As UInteger x, y, total
 
total = Heronian_triangles(200, 200, 200, result() )
 
' trim the array by removing empty entries
ReDim Preserve result(1 To total ) As triangle
 
sort_tri(result(), total)
 
Print "There are ";total;" Heronian triangles with sides <= 200"
Line 829 ⟶ 1,980:
For x = 1 To IIf(total > 9, 10, total)
With result(x)
Print Using " #####"; .a; .b; .c; .s; .area
End With
Next
Line 840 ⟶ 1,991:
With result(x)
If .area = 210 Then
Print Using " #####"; .a; .b; .c; .s; .area
End If
End With
Next
 
 
' empty keyboard buffer
While Inkey <> "" : Var _key_ = Inkey : Wend
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>There are 517 Heronian triangles with sides <= 200
Line 880 ⟶ 2,030:
7 65 68 70 210
3 148 149 150 210</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
text,,,,,70// Set width of tabs
 
local fn gcd( a as long, b as long )
dim as long result
if ( b != 0 )
result = fn gcd( b, a mod b)
else
result = abs(a)
end if
end fn = result
 
begin globals
dim as long triangleInfo( 600, 4 )
end globals
 
local fn CalculateHeronianTriangles( numberToCheck as long ) as long
dim as long c, b, a, result, count : count = 0
dim as double s, area
for c = 1 to numberToCheck
for b = 1 to c
for a = 1 to b
s = ( a + b + c ) / 2
area = s * ( s - a ) * ( s - b ) * ( s - c )
if area > 0
area = sqr( area )
if area = int( area )
result = fn gcd( b, c )
result = fn gcd( a, result )
if result == 1
count++
triangleInfo( count, 0 ) = a
triangleInfo( count, 1 ) = b
triangleInfo( count, 2 ) = c
triangleInfo( count, 3 ) = 2 * s
triangleInfo( count, 4 ) = area
end if
end if
end if
next
next
next
end fn = count
 
dim as long i, k, count
 
count = fn CalculateHeronianTriangles( 200 )
 
print
print "Number of triangles:"; count
print
print "---------------------------------------------"
print "Side A", "Side B", "Side C", "Perimeter", "Area"
print "---------------------------------------------"
 
// Sort array
dim as Boolean flips : flips = _true
while ( flips = _true )
flips = _false
for i = 1 to count - 1
if triangleInfo( i, 4 ) > triangleInfo( i + 1, 4 )
for k = 0 to 4
swap triangleInfo( i, k ), triangleInfo( i + 1, k )
next
flips = _true
end if
next
wend
 
// Find first 10 heronian triangles
for i = 1 to 10
print triangleInfo( i, 0 ), triangleInfo( i, 1 ), triangleInfo( i, 2 ), triangleInfo( i, 3 ), triangleInfo( i, 4 )
next
print
print "Triangles with an area of 210:"
print
// Search for triangle with area of 210
for i = 1 to count
if triangleInfo( i, 4 ) == 210
print triangleInfo( i, 0 ), triangleInfo( i, 1 ), triangleInfo( i, 2 ), triangleInfo( i, 3 ), triangleInfo( i, 4 )
end if
next
 
HandleEvents
</syntaxhighlight>
 
Output:
<pre>
Number of triangles: 517
 
---------------------------------------------
Side A Side B Side C Perimeter Area
---------------------------------------------
3 4 5 12 6
5 5 6 16 12
5 5 8 18 12
4 13 15 32 24
5 12 13 30 30
9 10 17 36 36
3 25 26 54 36
7 15 20 42 42
10 13 13 36 60
8 15 17 40 60
 
Triangles with an area of 210:
 
17 25 28 70 210
20 21 29 70 210
12 35 37 84 210
17 28 39 84 210
7 65 68 140 210
3 148 149 300 210
</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"math"
"sort"
)
 
const (
n = 200
header = "\nSides P A"
)
 
func gcd(a, b int) int {
leftover := 1
var dividend, divisor int
if (a > b) { dividend, divisor = a, b } else { dividend, divisor = b, a }
 
for (leftover != 0) {
leftover = dividend % divisor
if (leftover > 0) {
dividend, divisor = divisor, leftover
}
}
return divisor
}
 
func is_heron(h float64) bool {
return h > 0 && math.Mod(h, 1) == 0.0
}
 
// by_area_perimeter implements sort.Interface for [][]int based on the area first and perimeter value
type by_area_perimeter [][]int
 
func (a by_area_perimeter) Len() int { return len(a) }
func (a by_area_perimeter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a by_area_perimeter) Less(i, j int) bool {
return a[i][4] < a[j][4] || a[i][4] == a[j][4] && a[i][3] < a[j][3]
}
 
func main() {
var l [][]int
for c := 1; c <= n; c++ {
for b := 1; b <= c; b++ {
for a := 1; a <= b; a++ {
if (gcd(gcd(a, b), c) == 1) {
p := a + b + c
s := float64(p) / 2.0
area := math.Sqrt(s * (s - float64(a)) * (s - float64(b)) * (s - float64(c)))
if (is_heron(area)) {
l = append(l, []int{a, b, c, p, int(area)})
}
}
}
}
}
 
fmt.Printf("Number of primitive Heronian triangles with sides up to %d: %d", n, len(l))
sort.Sort(by_area_perimeter(l))
fmt.Printf("\n\nFirst ten when ordered by increasing area, then perimeter:" + header)
for i := 0; i < 10; i++ { fmt.Printf("\n%3d", l[i]) }
 
a := 210
fmt.Printf("\n\nArea = %d%s", a, header)
for _, it := range l {
if (it[4] == a) {
fmt.Printf("\n%3d", it)
}
}
}</syntaxhighlight>
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter:
Sides P A
[ 3 4 5 12 6]
[ 5 5 6 16 12]
[ 5 5 8 18 12]
[ 4 13 15 32 24]
[ 5 12 13 30 30]
[ 9 10 17 36 36]
[ 3 25 26 54 36]
[ 7 15 20 42 42]
[ 10 13 13 36 60]
[ 8 15 17 40 60]
 
Area = 210
Sides P A
[ 17 25 28 70 210]
[ 20 21 29 70 210]
[ 12 35 37 84 210]
[ 17 28 39 84 210]
[ 7 65 68 140 210]
[ 3 148 149 300 210]</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import qualified Data.List as L
import Data.Maybe
import Data.Ord
Line 944 ⟶ 2,307:
mapM_ printTri $ take 10 tris
putStrLn ""
mapM_ printTri $ filter ((== 210) . fifth) tris</langsyntaxhighlight>
{{out}}
<pre>Heronian triangles found: 517
Line 971 ⟶ 2,334:
'''Hero's formula Implementation'''
 
<langsyntaxhighlight Jlang="j">a=: 0&{"1
b=: 1&{"1
c=: 2&{"1
Line 977 ⟶ 2,340:
area=: 2 %: s*(s-a)*(s-b)*(s-c) NB. Hero's formula
perim=: +/"1
isPrimHero=: (0&~: * (= <.@:+))@area * 1 = a +. b +. c</langsyntaxhighlight>
 
We exclude triangles with zero area, triangles with complex area, non-integer area, and triangles whose sides share a common integer multiple.
Line 985 ⟶ 2,348:
The implementation above uses the symbols as given in the formula at the top of the page, making it easier to follow along as well as spot any errors. That formula distinguishes between the individual sides of the triangles but J could easily treat these sides as a single entity or array. The implementation below uses this "typical J" approach:
 
<langsyntaxhighlight Jlang="j">perim=: +/"1
s=: -:@:perim
area=: [: %: s * [: */"1 s - ] NB. Hero's formula
isNonZeroInt=: 0&~: *. (= <.@:+)
isPrimHero=: isNonZeroInt@area *. 1 = +./&.|:</langsyntaxhighlight>
 
'''Required examples'''
 
<langsyntaxhighlight Jlang="j"> Tri=:(1-i.3)+"1]3 comb 202 NB. distinct triangles with sides <= 200
HeroTri=: (#~ isPrimHero) Tri NB. all primitive Heronian triangles with sides <= 200
 
Line 1,019 ⟶ 2,382:
17 28 39 _ 84 210
7 65 68 _ 140 210
3 148 149 _ 300 210</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">import java.util.ArrayList;
<lang Java>
 
import java.util.ArrayList;
public class Heron {
public static void main(String[] args) {
ArrayList<int[]> list = new ArrayList<int[]>();
 
for(int c = 1; c <= 200; c++){
for (int bc = 1; bc <= c200; bc++) {
for (int ab = 1; ab <= bc; ab++) {
for (int a = 1; a <= b; a++) {
if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c)
 
list.add(new int[]{a, b, c, a + b + c, (int)heronArea(a, b, c)});
if (gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c))){
}
int area = (int) heronArea(a, b, c);
}
list.add(new int[]{a, b, c, a + b + c, area});
}
}
sort(list);
}
System.out.printf("Number of primitive Heronian triangles with sides up to 200: %d\n\nFirst ten when ordered by increasing area, then perimeter:\nSides Perimeter Area", list.size());
for(int i = 0; i < 10; i++){ }
}
System.out.printf("\n%d x %d x %d %d %d",list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]);
sort(list);
}
 
System.out.printf("\n\nArea = 210\nSides Perimeter Area");
System.out.printf("Number of primitive Heronian triangles with sides up "
for(int i = 0; i < list.size(); i++){
+ "to 200: %d\n\nFirst ten when ordered by increasing area, then"
if(list.get(i)[4] == 210)
+ " perimeter:\nSides Perimeter Area", list.size());
System.out.printf("\n%d x %d x %d %d %d",list.get(i)[0], list.get(i)[1], list.get(i)[2], list.get(i)[3], list.get(i)[4]);
 
}
for (int i = 0; i < 10; i++) {
}
System.out.printf("\n%d x %d x %d %d %d",
public static double heronArea(int a, int b, int c){
list.get(i)[0], list.get(i)[1], list.get(i)[2],
double s = (a + b + c)/ 2f;
list.get(i)[3], list.get(i)[4]);
return Math.sqrt(s *(s -a)*(s - b)*(s - c));
}
}
 
public static boolean isHeron(double h){
System.out.printf("\n\nArea = 210\nSides Perimeter Area");
return h % 1 == 0 && h > 0;
for (int i = 0; i < list.size(); i++) {
}
if (list.get(i)[4] == 210)
public static int gcd(int a, int b){
System.out.printf("\n%d x %d x %d %d %d",
int leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a;
list.get(i)[0], list.get(i)[1], list.get(i)[2],
while(leftover != 0){
list.get(i)[3], list.get(i)[4]);
leftover = dividend % divisor;
}
if(leftover > 0){
}
dividend = divisor;
 
divisor = leftover;
public static double heronArea(int a, int b, int c) {
}
double s = (a + b + c) / 2f;
}
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
return divisor;
}
}
 
public static void sort(ArrayList<int[]> list){
public static boolean swappedisHeron(double =h) true;{
return h % 1 == 0 && h > 0;
int[] temp;
}
while(swapped){
 
swapped = false;
public static int gcd(int a, int b) {
for(int i = 1; i < list.size(); i++){
int leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a;
if(list.get(i)[4] < list.get(i - 1)[4] || list.get(i)[4] == list.get(i - 1)[4] && list.get(i)[3] < list.get(i - 1)[3]){
while (leftover != 0) {
temp = list.get(i);
leftover = dividend % divisor;
list.set(i, list.get(i - 1));
if (leftover > 0) {
list.set(i - 1, temp);
dividend = divisor;
swapped = true;
divisor = leftover;
}
}
}
}
}
return divisor;
}
}
}
 
</lang>
public static void sort(ArrayList<int[]> list) {
boolean swapped = true;
int[] temp;
while (swapped) {
swapped = false;
for (int i = 1; i < list.size(); i++) {
if (list.get(i)[4] < list.get(i - 1)[4] ||
list.get(i)[4] == list.get(i - 1)[4] &&
list.get(i)[3] < list.get(i - 1)[3]) {
temp = list.get(i);
list.set(i, list.get(i - 1));
list.set(i - 1, temp);
swapped = true;
}
}
}
}
}</syntaxhighlight>
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
<lang>
Number of primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter:
Line 1,105 ⟶ 2,485:
17 x 28 x 39 84 210
7 x 65 x 68 140 210
3 x 148 x 149 300 210</pre>
</lang>
 
=={{header|JavaScript}}==
Line 1,112 ⟶ 2,491:
===Imperative===
 
<syntaxhighlight lang="javascript">
<lang JavaScript>
window.onload = function(){
var list = [];
Line 1,163 ⟶ 2,542:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
<lang>
Primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter:
Line 1,188 ⟶ 2,566:
17 x 28 x 39 84 210
7 x 65 x 68 140 210
3 x 148 x 149 300 210</pre>
</lang>
 
===Functional (ES5)===
Line 1,202 ⟶ 2,579:
ES6 JavaScript introduces syntactic sugar for list comprehensions, but the list monad pattern can already be used in ES5 – indeed in any language which supports the use of higher-order functions.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (n) {
var chain = function (xs, f) { // Monadic bind/chain
Line 1,283 ⟶ 2,660:
) + '\n\n';
})(200);</langsyntaxhighlight>
 
Output:
 
{{out}}
Found: 517 primitive Heronian triangles with sides up to 200.
 
Line 1,339 ⟶ 2,715:
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># input should be an array of the lengths of the sides
def hero:
(add/2) as $s
Line 1,378 ⟶ 2,754:
( .[] | select( hero == 210 ) | "\(rjust(11)) \(add|rjust(3)) \(hero|rjust(4))" ) ;
 
task(200)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ time jq -n -r -f heronian.jq
The number of primitive Heronian triangles with sides up to 200: 517
The first ten when ordered by increasing area, then perimeter, then maximum sides:
Line 1,401 ⟶ 2,777:
[17,28,39] 84 210
[7,65,68] 140 210
[3,148,149] 300 210</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 1,407 ⟶ 2,783:
 
'''Types and Functions'''
<syntaxhighlight lang="julia">
<lang Julia>
type IntegerTriangle{T<:Integer}
a::T
Line 1,434 ⟶ 2,810:
σ^2 == t
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
slim = 200
 
Line 1,471 ⟶ 2,847:
println(@sprintf "%6d %3d %3d %4d %4d" t.a t.b t.c t.σ t.p)
end
</syntaxhighlight>
</lang>
 
{{out}}
<pre>The number of primitive Hernonian triangles having sides ≤ 200 is 517
<pre>
The number of primitive Hernonian triangles having sides ≤ 200 is 517
 
Tabulating the first (by σ, p, c) 10 of these:
Line 1,497 ⟶ 2,872:
17 28 39 210 84
7 65 68 210 140
3 148 149 210 300</pre>
 
=={{header|Kotlin}}==
{{trans|Scala}}
<syntaxhighlight lang="scala">import java.util.ArrayList
 
object Heron {
private val n = 200
 
fun run() {
val l = ArrayList<IntArray>()
for (c in 1..n)
for (b in 1..c)
for (a in 1..b)
if (gcd(gcd(a, b), c) == 1) {
val p = a + b + c
val s = p / 2.0
val area = Math.sqrt(s * (s - a) * (s - b) * (s - c))
if (isHeron(area))
l.add(intArrayOf(a, b, c, p, area.toInt()))
}
print("Number of primitive Heronian triangles with sides up to $n: " + l.size)
 
sort(l)
print("\n\nFirst ten when ordered by increasing area, then perimeter:" + header)
for (i in 0 until 10) {
print(format(l[i]))
}
val a = 210
print("\n\nArea = $a" + header)
l.filter { it[4] == a }.forEach { print(format(it)) }
}
 
private fun gcd(a: Int, b: Int): Int {
var leftover = 1
var dividend = if (a > b) a else b
var divisor = if (a > b) b else a
while (leftover != 0) {
leftover = dividend % divisor
if (leftover > 0) {
dividend = divisor
divisor = leftover
}
}
return divisor
}
 
fun sort(l: MutableList<IntArray>) {
var swapped = true
while (swapped) {
swapped = false
for (i in 1 until l.size)
if (l[i][4] < l[i - 1][4] || l[i][4] == l[i - 1][4] && l[i][3] < l[i - 1][3]) {
val temp = l[i]
l[i] = l[i - 1]
l[i - 1] = temp
swapped = true
}
}
}
 
private fun isHeron(h: Double) = h.rem(1) == 0.0 && h > 0
 
private val header = "\nSides Perimeter Area"
private fun format(a: IntArray) = "\n%3d x %3d x %3d %5d %10d".format(a[0], a[1], a[2], a[3], a[4])
}
 
fun main(args: Array<String>) = Heron.run()</syntaxhighlight>
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter:
Sides Perimeter Area
3 x 4 x 5 12 6
5 x 5 x 6 16 12
5 x 5 x 8 18 12
4 x 13 x 15 32 24
5 x 12 x 13 30 30
9 x 10 x 17 36 36
3 x 25 x 26 54 36
7 x 15 x 20 42 42
10 x 13 x 13 36 60
8 x 15 x 17 40 60
 
Area = 210
Sides Perimeter Area
17 x 25 x 28 70 210
20 x 21 x 29 70 210
12 x 35 x 37 84 210
17 x 28 x 39 84 210
7 x 65 x 68 140 210
3 x 148 x 149 300 210</pre>
 
=={{header|Logtalk}}==
 
Implemented as a parametric object, the solution to making primitive Heronian triangles would look something like this:
 
<syntaxhighlight lang="logtalk">
% In this example we assume that A<=B<=C.
% Non-pedagogical code would verify and force this.
:- object(triangle(_A_, _B_, _C_)).
 
:- public([a/1, b/1, c/1, area/1, perimeter/1, primitive/0]).
 
a(_A_). b(_B_). c(_C_).
 
area(A) :-
AB is _A_ + _B_,
AB @> _C_, % you can't make a triangle if one side is half or longer the perimeter
s(S),
A is sqrt(S * (S - _A_) * (S - _B_) * (S - _C_)).
 
perimeter(P) :-
P is _A_ + _B_ + _C_.
 
primitive :- heronian, gcd(1).
 
% helper predicates
 
heronian :-
integer(_A_),
integer(_B_),
integer(_C_),
area(A),
A > 0.0,
0.0 is float_fractional_part(A).
 
gcd(G) :- G is gcd(_A_, gcd(_B_, _C_)).
 
s(S) :- perimeter(P), S is P / 2.
 
:- end_object.
</syntaxhighlight>
 
A quickly hacked-together test that produces the output for the task assignment would look something like this:
 
<syntaxhighlight lang="logtalk">
:- object(test_triangle).
 
:- uses(integer, [between/3]).
:- uses(list, [length/2, member/2, sort/3, take/3]).
:- uses(logtalk, [print_message(information, heronian, Message) as print(Message)]).
 
:- public(start/0).
 
start :-
 
gather_primitive_heronians(Primitives),
length(Primitives, L),
print('There are ~w primitive Heronian triangles with sides under 200.~n'+[L]),
 
sort(order_by(area), Primitives, AreaSorted),
take(10, AreaSorted, Area10),
print(@'The first ten found, ordered by area, are:\n'),
display_each_element(Area10),
 
sort(order_by(perimeter), Primitives, PerimeterSorted),
take(10, PerimeterSorted, Perimeter10),
print(@'The first ten found, ordered by perimeter, are:\n'),
display_each_element(Perimeter10),
 
findall(
t(A, B, C, 210.0, Perimeter),
member(t(A, B, C, 210.0, Perimeter), Primitives),
Area210
),
print(@'The list of those with an area of 210 is:\n'),
display_each_element(Area210).
 
% localized helper predicates
 
% display a single element in the provided format
display_single_element(t(A,B,C,Area,Perimeter)) :-
format(F),
print(F+[A, B, C, Area, Perimeter]).
 
% display each element in a list of elements, printing a header first
display_each_element(L) :-
print(@' A B C Area Perimeter'),
print(@'=== === === ======= ========='),
forall(member(T, L), display_single_element(T)),
print(@'\n').
 
format('~|~` t~w~3+~` t~w~4+~` t~w~4+~` t~w~8+~` t~w~7+').
 
% collect all the primitive heronian triangles within the boundaries of the provided task
gather_primitive_heronians(Primitives) :-
findall(
t(A, B, C, Area, Perimeter),
(
between(3, 200, A),
between(A, 200, B),
between(B, 200, C),
triangle(A, B, C)::primitive,
triangle(A, B, C)::area(Area),
triangle(A, B, C)::perimeter(Perimeter)
),
Primitives
).
 
order_by(_, =, T, T) :- !.
order_by(area, <, t(_,_,_,Area1,_), t(_,_,_,Area2,_)) :- Area1 < Area2, !.
order_by(area, >, t(_,_,_,Area1,_), t(_,_,_,Area2,_)) :- Area1 > Area2, !.
order_by(perimeter, <, t(_,_,_,_,Perimeter1), t(_,_,_,_,Perimeter2)) :- Perimeter1 < Perimeter2, !.
order_by(perimeter, >, t(_,_,_,_,Perimeter1), t(_,_,_,_,Perimeter2)) :- Perimeter1 > Perimeter2, !.
order_by(_, <, t(A1,_,_,_,_), t(A2,_,_,_,_)) :- A1 < A2, !.
order_by(_, <, t(_,B1,_,_,_), t(_,B2,_,_,_)) :- B1 < B2, !.
order_by(_, <, t(_,_,C1,_,_), t(_,_,C2,_,_)) :- C1 < C2, !.
order_by(_, >, _, _).
 
:- end_object.
</syntaxhighlight>
 
{{Out}}
 
<pre>
?- test_triangle::start.
% There are 517 primitive Heronian triangles with sides under 200.
 
% The first ten found, ordered by area, are:
 
% A B C Area Perimeter
% === === === ======= =========
% 3 4 5 6.0 12
% 5 5 6 12.0 16
% 5 5 8 12.0 18
% 4 13 15 24.0 32
% 5 12 13 30.0 30
% 3 25 26 36.0 54
% 9 10 17 36.0 36
% 7 15 20 42.0 42
% 6 25 29 60.0 60
% 8 15 17 60.0 40
%
 
% The first ten found, ordered by perimeter, are:
 
% A B C Area Perimeter
% === === === ======= =========
% 3 4 5 6.0 12
% 5 5 6 12.0 16
% 5 5 8 12.0 18
% 5 12 13 30.0 30
% 4 13 15 24.0 32
% 9 10 17 36.0 36
% 10 13 13 60.0 36
% 8 15 17 60.0 40
% 7 15 20 42.0 42
% 13 14 15 84.0 42
%
 
% The list of those with an area of 210 is:
 
% A B C Area Perimeter
% === === === ======= =========
% 3 148 149 210.0 300
% 7 65 68 210.0 140
% 12 35 37 210.0 84
% 17 25 28 210.0 70
% 17 28 39 210.0 84
% 20 21 29 210.0 70
%
 
true.
</pre>
 
=={{header|NimLua}}==
<syntaxhighlight lang="lua">-- Returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one
<lang nim>import math, algorithm, strfmt, sequtils
local function tryHt( a, b, c )
local result
local s = ( a + b + c ) / 2;
local areaSquared = s * ( s - a ) * ( s - b ) * ( s - c );
if areaSquared > 0 then
-- a, b, c does form a triangle
local area = math.sqrt( areaSquared );
if math.floor( area ) == area then
-- the area is integral so the triangle is Heronian
result = { a = a, b = b, c = c, perimeter = a + b + c, area = area }
end
end
return result
end
 
-- Returns the GCD of a and b
type
local function gcd( a, b ) return ( b == 0 and a ) or gcd( b, a % b ) end
HeronianTriangle = tuple
a: int
b: int
c: int
s: float
A: int
 
-- Prints the details of the Heronian triangle t
proc `$` (t: HeronianTriangle): string =
local function fmthtPrint("{:3d}, {:3d}, {:3d}\t{:3 ) print( string.3f}\t{:3d}format( "%4d %4d %4d %4d %4d", t.a, t.b, t.c, t.sarea, t.Aperimeter ) ) end
-- Prints headings for the Heronian Triangle table
local function htTitle() print( " a b c area perimeter" ); print( "---- ---- ---- ---- ---------" ) end
proc hero(a:int, b:int, c:int): tuple[s, A: float] =
let s: float = (a + b + c) / 2
result = (s, sqrt( s * (s - float(a)) * (s - float(b)) * (s - float(c)) ))
proc isHeronianTriangle(x: float): bool = ceil(x) == x and x.toInt > 0
 
-- Construct ht as a table of the Heronian Triangles with sides up to 200
proc gcd(x: int, y: int): int =
local ht = {};
var
for c = 1, 200 do
(dividend, divisor) = if x > y: (x, y) else: (y, x)
remainderfor b = dividend1, modc divisordo
for a = 1, b do
local t = gcd( gcd( a, b ), c ) == 1 and tryHt( a, b, c );
while remainder != 0:
if t then
dividend = divisor
ht[ #ht + 1 ] = t
divisor = remainder
remainder = dividend mod divisor end
result = divisor end
end
end
var list = newSeq[HeronianTriangle]()
const max = 200
 
-- sort the table on ascending area, perimiter and max side length
for c in 1..max:
-- note we constructed the triangles with c as the longest side
for b in 1..c:
table.sort( ht, function( a, b )
for a in 1..b:
return a.area < b.area or ( a.area == b.area
let (s, A) = hero(a, b, c)
and ( a.perimeter < b.perimeter
if isHeronianTriangle(A) and gcd(a, gcd(b, c)) == 1:
or ( a.perimiter == b.perimiter
let t:HeronianTriangle = (a, b, c, s, A.toInt)
and a.c < b.c
list.add(t)
)
)
)
end
);
 
-- Display the triangles
print( "There are " .. #ht .. " Heronian triangles with sides up to 200" );
htTitle();
for htPos = 1, 10 do htPrint( ht[ htPos ] ) end
print( " ..." );
print( "Heronian triangles with area 210:" );
htTitle();
for htPos = 1, #ht do
local t = ht[ htPos ];
if t.area == 210 then htPrint( t ) end
end</syntaxhighlight>
{{out}}
<pre>
There are 517 Heronian triangles with sides up to 200
a b c area perimeter
---- ---- ---- ---- ---------
3 4 5 6 12
5 5 6 12 16
5 5 8 12 18
4 13 15 24 32
5 12 13 30 30
9 10 17 36 36
3 25 26 36 54
7 15 20 42 42
10 13 13 60 36
8 15 17 60 40
...
Heronian triangles with area 210:
a b c area perimeter
---- ---- ---- ---- ---------
17 25 28 210 70
20 21 29 210 70
12 35 37 210 84
17 28 39 210 84
7 65 68 210 140
3 148 149 210 300
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[Heron]
Heron[a_, b_, c_] := With[{s = (a + b + c)/2}, Sqrt[s (s - a) (s - b) (s - c)]]
PrintTemporary[Dynamic[{a, b, c}]];
results = Reap[
Do[
If[a < b + c \[And] b < c + a \[And] c < a + b,
If[GCD[a, b, c] == 1,
If[IntegerQ[Heron[a, b, c]],
Sow[<|"Sides" -> {a, b, c}, "Area" -> Heron[a, b, c],
"Perimeter" -> a + b + c, "MaximumSide" -> Max[a, b, c]|>]
]
]
]
,
{a, 1, 200},
{b, a, 200},
{c, b, 200}
]
][[2, 1]];
results = SortBy[results, {#["Area"] &, #["Perimeter"] &, #["MaximumSide"] &}];
results // Length
Take[results, 10] // Dataset
Select[results, #["Area"] == 210 &] // Dataset</syntaxhighlight>
{{out}}
<pre>517
 
Sides Area Perimeter MaximumSide
{3,4,5} 6 12 5
{5,5,6} 12 16 6
{5,5,8} 12 18 8
{4,13,15} 24 32 15
{5,12,13} 30 30 13
{9,10,17} 36 36 17
{3,25,26} 36 54 26
{7,15,20} 42 42 20
{10,13,13} 60 36 13
{8,15,17} 60 40 17
 
Sides Area Perimeter MaximumSide
{17,25,28} 210 70 28
{20,21,29} 210 70 29
{12,35,37} 210 84 37
{17,28,39} 210 84 39
{7,65,68} 210 140 68
{3,148,149} 210 300 149</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import std/[math, algorithm, lenientops, strformat, sequtils]
 
type HeronianTriangle = tuple[a, b, c: int; p: int; area: int]
 
# Functions with three operands.
echo "Numbers of Heronian Triangle : ", list.len
func max(a, b, c: int): int = max(a, max(b, c))
func gcd(a, b, c: int): int = gcd(a, gcd(b, c))
 
list.sort dofunc cmp(x, y: HeronianTriangle): ->int int:=
## Compare two Heronian triangles.
result = cmp(x.A, y.A)
result = cmp(x.area, y.area)
if result == 0:
result = cmp(x.sp, y.sp)
if result == 0:
result = cmp(max(x.a, x.b, x.c), max(y.a, y.b, y.c))
 
func `$`(t: HeronianTriangle): string =
echo "Ten first Heronian triangle ordered : "
## Return the representation of a Heronian triangle.
echo "Sides Perimeter Area"
fmt"{t.a:3d}, {t.b:3d}, {t.c:3d} {t.p:7d} {t.area:8d}"
for t in list[0 .. <10]:
echo t
 
 
echo "Heronian triangle ordered with Area 210 : "
func hero(a, b, c: int): float =
echo "Sides Perimeter Area"
## Return the area of a triangle using Hero's formula.
for t in list.filter(proc (x: HeronianTriangle): bool = x.A == 210):
let s = (a + b + c) / 2
echo t</lang>
result = sqrt(s * (s - a) * (s - b) * (s - c))
 
func isHeronianTriangle(x: float): bool = x > 0 and ceil(x) == x
 
const Header = " Sides Perimeter Area\n------------- --------- ----"
 
var list: seq[HeronianTriangle]
const Max = 200
 
for c in 1..Max:
for b in 1..c:
for a in 1..b:
let area = hero(a, b, c)
if area.isHeronianTriangle and gcd(a, b, c) == 1:
let t: HeronianTriangle = (a, b, c, a + b + c, area.toInt)
list.add t
 
list.sort(cmp)
echo "Number of Heronian triangles: ", list.len
 
echo "\nOrdered list of first ten Heronian triangles:"
echo Header
for t in list[0 ..< 10]: echo t
 
echo "\nOrdered list of Heronian triangles with area 210:"
echo Header
for t in list.filterIt(it.area == 210): echo t
</syntaxhighlight>
{{out}}
<pre>NumbersNumber of Heronian Triangle triangles: 517
 
Ten first Heronian triangle ordered :
Ordered list of first ten Heronian triangles:
Sides Perimeter Area
3, Sides 4, 5 6.000 6Perimeter Area
------------- --------- ----
5, 5, 6 8.000 12
53, 54, 8 9.000 5 12 6
45, 13 5, 15 6 16.000 24 12
5, 12 5, 13 15.000 308 18 12
94, 1013, 17 18.000 15 36 32 24
35, 2512, 26 27.000 13 36 30 30
79, 1510, 20 21.000 17 42 36 36
10 3, 1325, 13 18.000 26 54 6036
87, 15, 17 20.000 60 42 42
10, 13, 13 36 60
Heronian triangle ordered with Area 210 :
Sides 8, 15, 17 Perimeter Area 40 60
 
17, 25, 28 35.000 210
Ordered list of Heronian triangles with area 210:
20, 21, 29 35.000 210
Sides Perimeter Area
12, 35, 37 42.000 210
------------- --------- ----
17, 28, 39 42.000 210
17, 725, 65,28 68 70.000 210
20, 21, 29 70 210
3, 148, 149 150.000 210</pre>
12, 35, 37 84 210
17, 28, 39 84 210
7, 65, 68 140 210
3, 148, 149 300 210</pre>
 
=={{header|ooRexx}}==
Derived from REXX with some changes
<langsyntaxhighlight lang="rexx">/*REXX pgm generates primitive Heronian triangles by side length & area.*/
Call time 'R'
Numeric Digits 12
Line 1,723 ⟶ 3,493:
::requires rxmath library
::routine sqrt
Return rxCalcSqrt(arg(1),14)</langsyntaxhighlight>
{{out}}
<pre>517 primitive Heronian triangles found with side length up to 200 (inclusive).
Line 1,750 ⟶ 3,520:
=={{header|PARI/GP}}==
 
<langsyntaxhighlight lang="parigp">Heron(v)=my([a,b,c]=v); (a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c) \\ returns 16 times the squared area
is(a,b,c)=(a+b+c)%2==0 && gcd(a,gcd(b,c))==1 && issquare(Heron([a,b,c]))
v=List(); for(a=1,200,for(b=a+1,200,for(c=b+1,200, if(is(a,b,c),listput(v, [a,b,c])))));
Line 1,760 ⟶ 3,530:
vecsort(u, (a,b)->Heron(a)-Heron(b))
vecsort(u, (a,b)->vecsum(a)-vecsum(b))
vecsort(u, 3) \\ shortcut: order by third component</langsyntaxhighlight>
{{out}}
<pre>%1 = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [1, 5, 6], [1, 6, 7], [1, 7, 8], [1, 8, 9], [1, 9, 10], [1, 10, 11], [1, 11, 12]]
Line 1,768 ⟶ 3,538:
%5 = [[17, 25, 28], [20, 21, 29], [12, 35, 37], [17, 28, 39], [7, 65, 68], [3, 148, 149]]
%6 = [[17, 25, 28], [20, 21, 29], [12, 35, 37], [17, 28, 39], [7, 65, 68], [3, 148, 149]]</pre>
 
=={{header|Pascal}}==
{{Trans|Lua}}
<syntaxhighlight lang="pascal">program heronianTriangles ( input, output );
type
(* record to hold details of a Heronian triangle *)
Heronian = record a, b, c, area, perimeter : integer end;
refHeronian = ^Heronian;
 
var
 
ht : array [ 1 .. 1000 ] of refHeronian;
htCount, htPos : integer;
a, b, c, i : integer;
lower, upper : integer;
k, h, t : refHeronian;
swapped : boolean;
 
(* returns the details of the Heronian Triangle with sides a, b, c or nil if it isn't one *)
function tryHt( a, b, c : integer ) : refHeronian;
var
s, areaSquared, area : real;
t : refHeronian;
begin
s := ( a + b + c ) / 2;
areaSquared := s * ( s - a ) * ( s - b ) * ( s - c );
t := nil;
if areaSquared > 0 then begin
(* a, b, c does form a triangle *)
area := sqrt( areaSquared );
if trunc( area ) = area then begin
(* the area is integral so the triangle is Heronian *)
new(t);
t^.a := a; t^.b := b; t^.c := c; t^.area := trunc( area ); t^.perimeter := a + b + c
end
end;
tryHt := t
end (* tryHt *) ;
 
(* returns the GCD of a and b *)
function gcd( a, b : integer ) : integer;
begin
if b = 0 then gcd := a else gcd := gcd( b, a mod b )
end (* gcd *) ;
 
(* prints the details of the Heronian triangle t *)
procedure htPrint( t : refHeronian ) ; begin writeln( t^.a:4, t^.b:5, t^.c:5, t^.area:5, t^.perimeter:10 ) end;
(* prints headings for the Heronian Triangle table *)
procedure htTitle ; begin writeln( ' a b c area perimeter' ); writeln( '---- ---- ---- ---- ---------' ) end;
 
begin
(* construct ht as a table of the Heronian Triangles with sides up to 200 *)
htCount := 0;
for c := 1 to 200 do begin
for b := 1 to c do begin
for a := 1 to b do begin
if gcd( gcd( a, b ), c ) = 1 then begin
t := tryHt( a, b, c );
if t <> nil then begin
htCount := htCount + 1;
ht[ htCount ] := t
end
end
end
end
end;
 
(* sort the table on ascending area, perimeter and max side length *)
(* note we constructed the triangles with c as the longest side *)
lower := 1;
upper := htCount;
repeat
upper := upper - 1;
swapped := false;
for i := lower to upper do begin
h := ht[ i ];
k := ht[ i + 1 ];
if ( k^.area < h^.area ) or ( ( k^.area = h^.area )
and ( ( k^.perimeter < h^.perimeter )
or ( ( k^.perimeter = h^.perimeter )
and ( k^.c < h^.c )
)
)
)
then begin
ht[ i ] := k;
ht[ i + 1 ] := h;
swapped := true
end
end;
until not swapped;
 
(* display the triangles *)
writeln( 'There are ', htCount:1, ' Heronian triangles with sides up to 200' );
htTitle;
for htPos := 1 to 10 do htPrint( ht[ htPos ] );
writeln( ' ...' );
writeln( 'Heronian triangles with area 210:' );
htTitle;
for htPos := 1 to htCount do begin
t := ht[ htPos ];
if t^.area = 210 then htPrint( t )
end
end.</syntaxhighlight>
{{out}}
<pre>
There are 517 Heronian triangles with sides up to 200
a b c area perimeter
---- ---- ---- ---- ---------
3 4 5 6 12
5 5 6 12 16
5 5 8 12 18
4 13 15 24 32
5 12 13 30 30
9 10 17 36 36
3 25 26 36 54
7 15 20 42 42
10 13 13 60 36
8 15 17 60 40
...
Heronian triangles with area 210:
a b c area perimeter
---- ---- ---- ---- ---------
17 25 28 210 70
20 21 29 210 70
12 35 37 210 84
17 28 39 210 84
7 65 68 210 140
3 148 149 210 300
</pre>
 
=={{header|Perl}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use List::Util qw(max);
Line 1,833 ⟶ 3,733:
}
 
&main();</langsyntaxhighlight>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 1,856 ⟶ 3,756:
210 140 7×65×68
210 300 3×148×149</pre>
 
=={{header|Perl 6}}==
{{works with|rakudo|2015-10-26}}
<lang perl6>sub hero($a, $b, $c) {
my $s = ($a + $b + $c) / 2;
my $a2 = $s * ($s - $a) * ($s - $b) * ($s - $c);
$a2.sqrt;
}
sub heronian-area($a, $b, $c) {
$_ when Int given hero($a, $b, $c).narrow;
}
 
sub primitive-heronian-area($a, $b, $c) {
heronian-area $a, $b, $c
if 1 == [gcd] $a, $b, $c;
}
 
sub show(@measures) {
say " Area Perimeter Sides";
for @measures -> [$area, $perim, $c, $b, $a] {
printf "%6d %6d %12s\n", $area, $perim, "$a×$b×$c";
}
}
sub MAIN ($maxside = 200, $first = 10, $witharea = 210) {
my @h = sort gather
for 1 .. $maxside -> $c {
for 1 .. $c -> $b {
for $c - $b + 1 .. $b -> $a {
if primitive-heronian-area($a,$b,$c) -> $area {
take [$area, $a+$b+$c, $c, $b, $a];
}
}
}
}
 
say "Primitive Heronian triangles with sides up to $maxside: ", +@h;
 
say "\nFirst $first:";
show @h[^$first];
 
say "\nArea $witharea:";
show @h.grep: *[0] == $witharea;
}</lang>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
 
First 10:
Area Perimeter Sides
6 12 3×4×5
12 16 5×5×6
12 18 5×5×8
24 32 4×13×15
30 30 5×12×13
36 36 9×10×17
36 54 3×25×26
42 42 7×15×20
60 36 10×13×13
60 40 8×15×17
 
Area 210:
Area Perimeter Sides
210 70 17×25×28
210 70 20×21×29
210 84 12×35×37
210 84 17×28×39
210 140 7×65×68
210 300 3×148×149</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
<lang Phix>function heroArea(integer a, b, c)
<span style="color: #008080;">function</span> <span style="color: #000000;">heroArea</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
atom s = (a+b+c)/2
<span style="color: #004080;">atom</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span>
return sqrt(s*(s-a)*(s-b)*(s-c))
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">-</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)*(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">-</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)*(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">-</span><span style="color: #000000;">c</span><span style="color: #0000FF;">),</span><span style="color: #000000;">0</span><span style="color: #0000FF;">))</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function hero(atom h)
<span style="color: #008080;">function</span> <span style="color: #000000;">hero</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">)</span>
return remainder(h,1)=0 and h>0
<span style="color: #008080;">return</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
sequence list = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
integer tries = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">tries</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for a=1 to 200 do
<span style="color: #008080;">for</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">200</span> <span style="color: #008080;">do</span>
for b=1 to a do
<span style="color: #008080;">for</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">a</span> <span style="color: #008080;">do</span>
for c=1 to b do
<span style="color: #008080;">for</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">b</span> <span style="color: #008080;">do</span>
tries += 1
<span style="color: #000000;">tries</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if gcd({a,b,c})=1 then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">gcd</span><span style="color: #0000FF;">({</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">})=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
atom hArea = heroArea(a,b,c)
<span style="color: #004080;">atom</span> <span style="color: #000000;">hArea</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">heroArea</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
if hero(hArea) then
<span style="color: #008080;">if</span> <span style="color: #000000;">hero</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hArea</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
list = append(list,{hArea,a+b+c,a,b,c})
<span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">hArea</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">})</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
list = sort(list)
<span style="color: #000000;">list</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">)</span>
printf(1,"Primitive Heronian triangles with sides up to 200: %d (of %,d tested)\n\n",{length(list),tries})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Primitive Heronian triangles with sides up to 200: %d (of %,d tested)\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">),</span><span style="color: #000000;">tries</span><span style="color: #0000FF;">})</span>
printf(1,"First 10 ordered by area/perimeter/sides:\n")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First 10 ordered by area/perimeter/sides:\n"</span><span style="color: #0000FF;">)</span>
printf(1,"area perimeter sides")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"area perimeter sides\n"</span><span style="color: #0000FF;">)</span>
for i=1 to 10 do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">10</span> <span style="color: #008080;">do</span>
printf(1,"\n%4d %3d %dx%dx%d",list[i])
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%4d %3d %dx%dx%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"\n\narea = 210:\n")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\narea = 210:\n"</span><span style="color: #0000FF;">)</span>
printf(1,"area perimeter sides")
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"area perimeter sides\n"</span><span style="color: #0000FF;">)</span>
for i=1 to length(list) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
if list[i][1]=210 then
<span style="color: #008080;">if</span> <span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">210</span> <span style="color: #008080;">then</span>
printf(1,"\n%4d %3d %dx%dx%d",list[i])
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%4d %3d %dx%dx%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">list</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,993 ⟶ 3,826:
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
function Get-Gcd($a, $b){
if($a -ge $b){
Line 2,041 ⟶ 3,874:
}
}
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
Primitive Heronian triangles with sides up to 200: 517
 
Line 2,067 ⟶ 3,900:
7 65 68 140 210
3 148 149 300 210
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">from __future__ import division, print_function
from math import gcd, sqrt
from fractions import gcd
from itertools import product
 
 
def hero(a, b, c):
s = (a + b + c) / 2
a2 = s * (s - a) * (s - b) * (s - c)
return sqrt(a2) if a2 > 0 else 0
 
 
def is_heronian(a, b, c):
a = hero(a, b, c)
return a > 0 and a.is_integer()
 
 
def gcd3(x, y, z):
def gcd3(x, y, z):
return gcd(gcd(x, y), z)
 
 
if __name__ == '__main__':
maxsideMAXSIDE = 200
 
h = [(a, b, c) for a,b,c in product(range(1, maxside + 1), repeat=3)
N = 1 + MAXSIDE
if a <= b <= c and a + b > c and gcd3(a, b, c) == 1 and is_heronian(a, b, c)]
h = [(x, y, z)
h.sort(key = lambda x: (hero(*x), sum(x), x[::-1])) # By increasing area, perimeter, then sides
for x in range(1, N)
print('Primitive Heronian triangles with sides up to %i:' % maxside, len(h))
for y in range(x, N)
print('\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:')
for z in range(y, N) if (x + y > z) and
print('\n'.join(' %14r perim: %3i area: %i'
1 == gcd3(x, y, z) and
is_heronian(x, y, z)]
 
# By increasing area, perimeter, then sides
h.sort(key=lambda x: (hero(*x), sum(x), x[::-1]))
 
print(
'Primitive Heronian triangles with sides up to %i:' % MAXSIDE, len(h)
)
print('\nFirst ten when ordered by increasing area, then perimeter,',
'then maximum sides:')
print('\n'.join(' %14r perim: %3i area: %i'
% (sides, sum(sides), hero(*sides)) for sides in h[:10]))
print('\nAll with area 210 subject to the previous ordering:')
print('\n'.join(' %14r perim: %3i area: %i'
% (sides, sum(sides), hero(*sides)) for sides in h
if hero(*sides) == 210))</lang>
</syntaxhighlight>
 
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 2,133 ⟶ 3,976:
Mostly adopted from Python implementation:
 
<syntaxhighlight lang="r">
<lang R>
area <- function(a, b, c) {
s = (a + b + c) / 2
Line 2,170 ⟶ 4,013:
cat("Showing the first ten ordered first by perimeter, then by area:\n")
print(head(r[order(x=r[,"perimeter"],y=r[,"area"]),],n=10))
</syntaxhighlight>
</lang>
 
{{out}}
 
<syntaxhighlight lang="text">There are 517 Heronian triangles up to a maximal side length of 200.
Showing the first ten ordered first by perimeter, then by area:
a b c perimeter area
Line 2,186 ⟶ 4,029:
[8,] 8 15 17 40 60
[9,] 7 15 20 42 42
[10,] 13 14 15 42 84</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="text">#lang at-exp racket
(require data/order scribble/html)
 
Line 2,234 ⟶ 4,077:
@; Show a similar ordered table for those triangles with area = 210
@(triangles->table (tri-sort (filter (λ(t) (eq? 210 (car t))) ts)))
}))</langsyntaxhighlight>
 
This program generates HTML, so the output is inline with the page, not in a <code>&lt;pre></code> block.
Line 2,263 ⟶ 4,106:
 
<br><br>
=={{header|REXX}}==
This REXX version makes use of these facts:
::::* &nbsp; if &nbsp; '''A''' &nbsp; is even, &nbsp; then &nbsp; '''B''' &nbsp; and &nbsp; '''C''' &nbsp; must be odd.
::::* &nbsp; if &nbsp; '''B''' &nbsp; is even, &nbsp; then &nbsp; '''C''' &nbsp; must be odd.
::::* &nbsp; if &nbsp; '''A''' &nbsp; and &nbsp; '''B''' &nbsp; are odd, &nbsp; then &nbsp; '''C''' &nbsp; must be even.
::::* &nbsp; with the above truisms, then &nbsp; '''C''' &nbsp; can be incremented by &nbsp; <big>'''2'''</big>.
 
=={{header|Raku}}==
Programming notes:
(formerly Perl 6)
{{works with|Rakudo|2018.09}}
<syntaxhighlight lang="raku" line>sub hero($a, $b, $c) {
my $s = ($a + $b + $c) / 2;
($s * ($s - $a) * ($s - $b) * ($s - $c)).sqrt;
}
sub heronian-area($a, $b, $c) {
$_ when Int given hero($a, $b, $c).narrow;
}
 
sub primitive-heronian-area($a, $b, $c) {
The &nbsp; '''hGCD''' &nbsp; subroutine is a specialized version of a GCD routine in that it doesn't check for non-positive integers; &nbsp; it also expects 3 arguments.
heronian-area $a, $b, $c
if 1 == [gcd] $a, $b, $c;
}
 
sub show(@measures) {
Also, a fair amount of code was added to optimize the speed &nbsp; (at the expense of program simplicity); &nbsp; by thoughtful ordering of
say " Area Perimeter Sides";
<br>the "elimination" checks, and also the use of an integer version of a &nbsp; SQRT &nbsp; subroutine, the execution time was greatly reduced
for @measures -> [$area, $perim, $c, $b, $a] {
<br>(by a factor of eight). &nbsp; Note that the &nbsp; '''hIsqrt''' &nbsp; ('''h'''eronian '''I'''nteger '''sq'''are '''r'''oo'''t''') &nbsp; subroutine doesn't use floating point.
printf "%6d %6d %12s\n", $area, $perim, "$a×$b×$c";
<br>['''hIsqrt''' &nbsp; is a modified version of an &nbsp; '''Isqrt''' &nbsp; function.]
}
}
sub MAIN ($maxside = 200, $first = 10, $witharea = 210) {
my @hh[1000];
my atomicint $i;
(1 .. $maxside).race(:12batch).map: -> $c {
for 1 .. $c -> $b {
for $c - $b + 1 .. $b -> $a {
if primitive-heronian-area($a,$b,$c) -> $area {
@hh[$i⚛++] = [$area, $a+$b+$c, $c, $b, $a];
}
}
}
}
 
my @h = (@hh.grep: so *).sort;
This REXX version doesn't need to explicitly sort the triangles.
<lang rexx>/*REXX program generates primitivesay "Primitive Heronian triangles bywith sides up sideto length$maxside: and", area.*/+@h;
 
parse arg N first area . /*get optional arguments from C.L.*/
say "\nFirst $first:";
if N=='' | N==',' then N=200 /*Not specified? Then use default.*/
show @h[^$first];
if first=='' | first==',' then first= 10 /* " " " " " */
 
if area=='' | area==',' then area=210 /* " " " " " */
say "\nArea $witharea:";
numeric digits 99; numeric digits max(9, 1+length(N**5)) /*ensure 'nuff digs.*/
show @h.grep: *[0] == $witharea;
call Heron; HT='Heronian triangles' /*invoke the Heron subroutine. */
}</syntaxhighlight>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
 
First 10:
Area Perimeter Sides
6 12 3×4×5
12 16 5×5×6
12 18 5×5×8
24 32 4×13×15
30 30 5×12×13
36 36 9×10×17
36 54 3×25×26
42 42 7×15×20
60 36 10×13×13
60 40 8×15×17
 
Area 210:
Area Perimeter Sides
210 70 17×25×28
210 70 20×21×29
210 84 12×35×37
210 84 17×28×39
210 140 7×65×68
210 300 3×148×149</pre>
 
=={{header|REXX}}==
=== using iSQRT ===
This REXX version makes use of these facts:
:::* &nbsp; if &nbsp; '''A''' &nbsp; is even, &nbsp; then &nbsp; '''B''' &nbsp; and &nbsp; '''C''' &nbsp; must be odd.
:::* &nbsp; if &nbsp; '''B''' &nbsp; is even, &nbsp; then &nbsp; '''C''' &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; must be odd.
:::* &nbsp; if &nbsp; '''A''' &nbsp; and &nbsp; '''B''' &nbsp; are odd, &nbsp; then &nbsp; '''C''' &nbsp; must be even.
:::* &nbsp; with the 1<sup>st</sup> three truisms, then:
::::::* &nbsp; '''C''' &nbsp; can be incremented by &nbsp; <big>'''2'''</big>.
::::::* &nbsp; the area is always even.
 
Programming notes:
The &nbsp; '''hGCD''' &nbsp; subroutine is a specialized version of a '''GCD''' routine in that:
:::* &nbsp; it doesn't check for non-positive integers
:::* &nbsp; it expects exactly three arguments
Also, a fair amount of code was added to optimize the speed &nbsp; (at the expense of program simplicity).
By thoughtful ordering of the elimination checks, and also the use of an &nbsp; ''integer version'' &nbsp;
of a &nbsp; '''SQRT'''
<br>subroutine, &nbsp; the execution time was greatly reduced &nbsp; (by a factor of eight).
Note that the &nbsp; '''hIsqrt''' &nbsp; ('''h'''eronian '''I'''nteger '''sq'''are '''r'''oo'''t''') &nbsp;
subroutine doesn't use floating point.
<br>['''hIsqrt''' &nbsp; is a modified/simplified version of an &nbsp; '''Isqrt''' &nbsp; function.]
This REXX version doesn't need to explicitly sort the triangles as they are listed in the proper order.
<syntaxhighlight lang="rexx">/*REXX program generates & displays primitive Heronian triangles by side length and area*/
parse arg N first area . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 200 /*Not specified? Then use the default.*/
if first=='' | first=="," then first= 10 /* " " " " " " */
if area=='' | area=="," then area= 210 /* " " " " " " */
numeric digits 99 /*ensure 'nuff dec. digs to calc. N**5.*/
numeric digits max(9, 1 + length(N**5) ) /*minimize decimal digits for REXX pgm.*/
call Heron; HT= 'Heronian triangles' /*invoke the Heron subroutine. */
say # ' primitive' HT "found with sides up to " N ' (inclusive).'
call show , 'listingListing of the first ' first ' primitive' HT":"
call show area, 'listingListing of the (above) found primitive' HT "with an area of " area
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
Heron: @.=0; #=0; minP= 9e9; maxP= 0; maxA= 0; minA= 9e9; Ln= length(N) /* _ __*/
#= 0; #.= 0; #.2= 1; #.3= 1; #.7= 1; #.8= 1 /*digits ¬good √ */
do a=3 to N /*start at a minimum side length of 3. */
odd Aeven= a//2;==0 ev=\odd /*if A is even, B and C must be odd.*/
do b=a+evAeven to N by 1+evAeven; ab= a + b /*AB: is a shortcut for the sum of A & B. */
if b//2==0 then bump= 1 /*Is B even? /*B is even? Then C≡odd C is odd. */
else if oddAeven then bump=1 0 /*Is A /*ifeven? A and B odd, C≡even. " " " " */
else bump=0 1 /*A and B /*OKare both odd, biz is as usual. */
do c=b+bump to N by 2; s= (ab + c)/2 % 2 /*calculate triangle's perimeter: /*calculate Perimeter, S. */
_= s*(s-a)*(s-b)*(s-c); if _<=0 then iterate /*is _ isn't not positive,? Skip skip.it*/
parse var _ '.' -1 z ; ; if #.z\=='' then iterate /*Last digit not ansquare? integer, skip.Skip it*/
parse varar= hIsqrt(_); '' -1 z ; if #.z ar*ar\==_ then iterate /*lastIs area not an integer? dig ¬square,Skip skip.it*/
ar=hIsqrtif hGCD(_a, b, c); \== 1 if ar*ar\==_ then iterate /*areaGCD ¬of ansides integer,skip.not equal 1? Skip it*/
if hGCD(a,b,c)\=#= # + 1; thenp= ab + c iterate /*GCDprimitive Heronian triangle. of sides ¬ 1, skip.*/
#minP=#+1; min( p=ab+c, minP); maxP= max( p, maxP); Lp= /*primitive Heron triang.*/length(maxP)
minPminA= min( par,minP minA); maxP maxA= max( par,maxP maxA); Lp La= length(maxPmaxA)
_=@.ar.p.0 + 1 /*bump Heronian triangle counter. */
minA=min(ar,minA); maxA=max(ar,maxA); La=length(maxA); @.ar=
_=@.ar.p.0+1 = _; @.ar.p._= right(a, Ln) right(b, Ln) right(c, Ln) /*bump triangle counterunique. */
end /*c*/ /* [↑] keep each unique perimeter#*/
@.ar.p.0=_; @.ar.p._=right(a,Ln) right(b,Ln) right(c,Ln) /*unique.*/
end /*c*/ /* [↑] keep each unique perimeter #. */
end /*b*/
end /*a*/; return # /*return # of Heronian triangles. */
end /*a*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
return # /*return number of Heronian triangles. */
hGCD: x=a; do j=2 for 2; y= arg(j); do until y==0; parse value x//y y with y x
/*────────────────────────────────────────────────────────────────────────────*/
end /*until*/
hIsqrt: procedure; parse arg x; q=1;r=0; do while q<=x; q=q*4; end; do while q>1
q=q%4; _=x-r-q; r=r%2; if _>=0 then parse value _ r+q with xend r; end /*j*/; return rx
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
showhIsqrt: m=0procedure; parse arg sayx; sayq= 1; r= parse0; arg ae; say arg(2); if ae\= do while q<=''x; then first q=9e9 q * 4
end /*while q<=x*/
say; $=left('',9); $a=$"area:"; $p=$'perimeter:'; $s=$"sides:" /*literals*/
do i=minA do to maxAwhile q>1; ifq=q%4; ae\_=='' &x-r-q; i\=r=ae r%2; thenif iterate_>=0 then parse value _ r+q /*=with area?x */r
do j=minP end to maxP /*while until mq>=first1*/; /*only display the FIRST entries.*/ return r
/*──────────────────────────────────────────────────────────────────────────────────────*/
do k=1 for @.i.j.0; m=m+1 /*display each perimeter entry. */
show: m=0; say; say; parse arg sayae; right(m,9) $asay rightarg(i,La2); $p right(j,Lp) if ae\=='' $s then first= @.i.j.k9e9
say; $=left('',9); $a= $"area:"; $p= $'perimeter:'; $s= $"sides:" /*literals*/
end /*k*/
end do /*j*/ i=minA to maxA; if ae\=='' & i\==ae then iterate /*= [↑] use the known perimeters.area? */
end /*i*/ do j=minP to maxP until m>=first /*only [↑]display the show anyFIRST found trianglesentries. */
do k=1 for @.i.j.0; m= m + 1 /*display each perimeter entry. */
return
say right(m, 9) $a right(i, La) $p right(j, Lp) $s @.i.j.k
/*────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
end /*k*/
hGCD: procedure; parse arg x; do j=2 for 2; y=arg(j); do until y==0; parse value x//y y with y x; end; end; return x</lang>
end /*j*/ /* [↑] use the known perimeters. */
{{out}}
end /*i*/; return /* [↑] show any found triangles. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
517 primitive Heronian triangles found with sides up to 200 (inclusive).
 
 
listingListing of the first 10 primitive Heronian triangles:
 
1 area: 6 perimeter: 12 sides: 3 4 5
Line 2,350 ⟶ 4,280:
 
 
listingListing of the (above) found primitive Heronian triangles with an area of 210
 
1 area: 210 perimeter: 70 sides: 17 25 28
Line 2,358 ⟶ 4,288:
5 area: 210 perimeter: 140 sides: 7 65 68
6 area: 210 perimeter: 300 sides: 3 148 149
</pre>
 
===using SQRT table===
This REXX version makes use of a precalculated table of squares of some
integers &nbsp; (which are used to find square roots very quickly).
 
It is about eight times faster than the 1<sup>st</sup> REXX version.
<syntaxhighlight lang="rexx">/*REXX program generates & displays primitive Heronian triangles by side length and area*/
parse arg N first area . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 200 /*Not specified? Then use the default.*/
if first=='' | first=="," then first= 10 /* " " " " " " */
if area=='' | area=="," then area= 210 /* " " " " " " */
numeric digits 99; numeric digits max(9, 1+length(N**5)) /*ensure 'nuff decimal digits.*/
call Heron; HT= 'Heronian triangles' /*invoke the Heron subroutine. */
say # ' primitive' HT "found with sides up to " N ' (inclusive).'
call show , 'Listing of the first ' first ' primitive' HT":"
call show area, 'Listing of the (above) found primitive' HT "with an area of " area
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Heron: @.= 0; #= 0; !.= .; minP= 9e9; maxA= 0; maxP= 0; minA= 9e9; Ln= length(N)
do i=1 for N**2%2; _= i*i; !._= i /* __ */
end /*i*/ /* [↑] pre─calculate some fast √ */
do a=3 to N /*start at a minimum side length of 3. */
Aeven= a//2==0 /*if A is even, B and C must be odd.*/
do b=a+Aeven to N by 1+Aeven; ab= a + b /*AB: a shortcut for the sum of A & B. */
if b//2==0 then bump= 1 /*Is B even? Then C is odd. */
else if Aeven then bump= 0 /*Is A even? " " " " */
else bump= 1 /*A and B are both odd, biz as usual.*/
do c=b+bump to N by 2; s= (ab + c) % 2 /*calculate triangle's perimeter: S. */
_= s*(s-a)*(s-b)*(s-c); if !._==. then iterate /*Is _ not a square? Skip.*/
if hGCD(a,b,c) \== 1 then iterate /*GCD of sides not 1? Skip.*/
#= # + 1; p= ab + c; ar= !._ /*primitive Heronian triangle*/
minP= min( p, minP); maxP= max( p, maxP); Lp= length(maxP)
minA= min(ar, minA); maxA= max(ar, maxA); La= length(maxA); @.ar=
_= @.ar.p.0 + 1 /*bump the triangle counter. */
@.ar.p.0= _; @.ar.p._= right(a, Ln) right(b, Ln) right(c, Ln) /*unique*/
end /*c*/ /* [↑] keep each unique perimeter #. */
end /*b*/
end /*a*/; return # /*return number of Heronian triangles. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hGCD: x=a; do j=2 for 2; y= arg(j); do until y==0; parse value x//y y with y x
end /*until*/
end /*j*/; return x
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: m=0; say; say; parse arg ae; say arg(2); if ae\=='' then first= 9e9
say; $=left('',9); $a= $"area:"; $p= $'perimeter:'; $s= $"sides:" /*literals*/
do i=minA to maxA; if ae\=='' & i\==ae then iterate /*= area? */
do j=minP to maxP until m>=first /*only display the FIRST entries.*/
do k=1 for @.i.j.0; m= m + 1 /*display each perimeter entry. */
say right(m, 9) $a right(i, La) $p right(j, Lp) $s @.i.j.k
end /*k*/
end /*j*/ /* [↑] use the known perimeters. */
end /*i*/; return /* [↑] show any found triangles. */</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Heronian triangles
 
see "Heronian triangles with sides up to 200" + nl
see "Sides Perimeter Area" + nl
for n = 1 to 200
for m = n to 200
for p = m to 200
s = (n + m + p) / 2
w = sqrt(s * (s - n) * (s - m) * (s - p))
bool = (gcd(n, m) = 1 or gcd(n, m) = n) and (gcd(n, p) = 1 or gcd(n, p) = n) and (gcd(m, p) = 1 or gcd(m, p) = m)
if w = floor(w) and w > 0 and bool
see "{" + n + ", " + m + ", " + p + "}" + " " + s*2 + " " + w + nl
ok
next
next
next
see nl
 
see "Heronian triangles with area 210:" + nl
see "Sides Perimeter Area" + nl
for n = 1 to 150
for m = n to 150
for p = m to 150
s = (n + m + p) / 2
w = sqrt(s * (s - n) * (s - m) * (s - p))
bool = (gcd(n, m) = 1 or gcd(n, m) = n) and (gcd(n, p) = 1 or gcd(n, p) = n) and (gcd(m, p) = 1 or gcd(m, p) = m)
if w = 210 and bool
see "{" + n + ", " + m + ", " + p + "}" + " " + s*2 + " " + w + nl
ok
next
next
next
 
func gcd(gcd, b)
while b
c = gcd
gcd = b
b = c % b
end
return gcd
</syntaxhighlight>
Output:
<pre>
Heronian triangles with sides up to 200
Sides Perimeter Area
{3, 4, 5} 12 6
{3, 25, 26} 54 36
{4, 13, 15} 32 24
{5, 5, 6} 16 12
{5, 5, 8} 18 12
{5, 12, 13} 30 30
{7, 15, 20 } 42 42
{8, 15, 17} 40 60
{9, 10, 17} 36 36
{10, 13, 13} 36 60
{13, 13, 24} 50 60
 
Heronian triangles with area 210:
Sides Perimeter Area
{3, 148, 149} 300 210
{7, 65, 68} 140 210
{12, 35, 37} 84 210
{17, 25, 28} 70 210
{17, 28, 39} 84 210
{20, 21, 29} 70 210
</pre>
 
=={{header|RPL}}==
We use here the <code>→V3</code> and<code>SORT</code> instructions, available for HP-48G or newer models only. <code>GCD </code> is not a built-in instruction, but it is a question of a few words:
≪ WHILE DUP REPEAT SWAP OVER MOD END DROP ABS ≫ ''''GCD'''' STO
{{trans|FreeBASIC}}
{{works with|Halcyon Calc|4.2.8}}
{| class="wikitable"
! RPL code
! Comment
|-
|
3 DUPN + + 2 / → a b c s
≪ s DUP a - * s b - * s c - *
≫ ≫ ‘'''SURF2'''’ STO
IF '''SURF2''' DUP 0 > THEN √ FP NOT ELSE DROP 0 END
≫ ‘'''HERO?'''’ STO
≪ → n
≪ { } 1 n FOR x
x n FOR y
y x 2 MOD + x y + 1 - n MIN FOR z
IF x y z '''GCD GCD''' THEN
IF x y z '''HERO?''' THEN x y z →V3 +
END END
2 STEP NEXT NEXT
≫ ≫ ‘'''TASK2'''’ RCL
|
'''SURF2''' ''( a b c → A² ) ''
s = (a+b+c)/2
A² = s(s-a)(s-b)(s-c)
return A²
'''HERO?''' ''( a b c → boolean ) ''
return true if A > 0 and √A is an integer
'''TASK2''' ''( n → { [Heronians] ) ''
for x = 1 to n
for y = x to n
for z = y+u to min(x+y-1,n) // u ensures x+y+z is even
if gcd(x,y,z) == 1
if x y z is Heronian then append to list
z += 2 to keep x+y+z even
|}
The rest of the code, which is devoted to printing the requested tables, is boring and the result is awful: native RPL works on machines with a 22-character screen.
{{in}}
<pre>
≪ → a b c
≪ c →STR WHILE DUP SIZE 4 < REPEAT " " SWAP + END
a b c + + →STR SWAP + WHILE DUP SIZE 8 < REPEAT " " SWAP + END
a b c SURF √ →STR SWAP + WHILE DUP SIZE 12 < REPEAT " " SWAP + END
" (" + a →STR + " " + b →STR + " " + c →STR + ")" +
≫ ≫ 'PRTRI' STO
200 TASK2 'H' STO
≪ { } 1 H SIZE FOR j H j GET ARRY→ DROP PRTRI + NEXT SORT 'H2' STO ≫ EVAL
"Area P. LS (triangle)"
1 10 H2 SUB
≪ { } 1 H2 SIZE FOR j H2 j GET IF DUP 1 4 SUB " 210" == THEN + END NEXT ≫ EVAL
</pre>
{{out}}
<pre style="height:40ex;overflow:scroll;">
4: 517
3: "Area P. LS (triangle)"
2: { " 6 12 5 (3 4 5)"
" 12 16 6 (5 5 6)"
" 12 18 8 (5 5 8)"
" 24 32 15 (4 13 15)"
" 30 30 13 (5 12 13)"
" 36 36 17 (9 10 17)"
" 36 54 26 (3 25 26)"
" 42 42 20 (7 15 20)"
" 60 36 13 (10 13 13)"
" 60 40 17 (8 15 17)" }
1: { " 210 70 28 (17 25 28)"
" 210 70 29 (20 21 29)"
" 210 84 37 (12 35 37)"
" 210 84 39 (17 28 39)"
" 210 140 68 (7 65 68)"
" 210 300 149 (3 148 149)" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Triangle
def self.valid?(a,b,c) # class method
short, middle, long = [a, b, c].sort
Line 2,406 ⟶ 4,543:
puts sorted.first(10).map(&:to_s)
puts "\nTriangles with an area of: #{area}"
sorted.each{|tr| puts tr if tr.area == area}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,430 ⟶ 4,567:
7x65x68 140 210.0
3x148x149 300 210.0
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use num_integer::Integer;
use std::{f64, usize};
 
const MAXSIZE: usize = 200;
 
#[derive(Debug)]
struct HerionanTriangle {
a: usize,
b: usize,
c: usize,
area: usize,
perimeter: usize,
}
 
fn get_area(a: &usize, b: &usize, c: &usize) -> f64 {
let s = (a + b + c) as f64 / 2.;
(s * (s - *a as f64) * (s - *b as f64) * (s - *c as f64)).sqrt()
}
 
fn is_heronian(a: &usize, b: &usize, c: &usize) -> bool {
let area = get_area(a, b, c);
// Heronian if the area is an integer number
area != 0. && area.fract() == 0.
}
 
fn main() {
let mut heronians: Vec<HerionanTriangle> = vec![];
 
(1..=MAXSIZE).into_iter().for_each(|a| {
(a..=MAXSIZE).into_iter().for_each(|b| {
(b..=MAXSIZE).into_iter().for_each(|c| {
if a + b > c && a.gcd(&b).gcd(&c) == 1 && is_heronian(&a, &b, &c) {
heronians.push(HerionanTriangle {
a,
b,
c,
perimeter: a + b + c,
area: get_area(&a, &b, &c) as usize,
})
}
})
})
});
 
// sort by area then by perimeter, then by maximum side
heronians.sort_unstable_by(|x, y| {
x.area
.cmp(&y.area)
.then(x.perimeter.cmp(&y.perimeter))
.then((x.a.max(x.b).max(x.c)).cmp(&y.a.max(y.b).max(y.c)))
});
 
println!(
"Primitive Heronian triangles with sides up to 200: {}",
heronians.len()
);
 
println!("\nFirst ten when ordered by increasing area, then perimeter,then maximum sides:");
heronians.iter().take(10).for_each(|h| println!("{:?}", h));
 
println!("\nAll with area 210 subject to the previous ordering:");
heronians
.iter()
.filter(|h| h.area == 210)
.for_each(|h| println!("{:?}", h));
}
 
</syntaxhighlight>
{{out}}
<pre>
Primitive Heronian triangles with sides up to 200: 517
 
First ten when ordered by increasing area, then perimeter,then maximum sides:
HerionanTriangle { a: 3, b: 4, c: 5, area: 6, perimeter: 12 }
HerionanTriangle { a: 5, b: 5, c: 6, area: 12, perimeter: 16 }
HerionanTriangle { a: 5, b: 5, c: 8, area: 12, perimeter: 18 }
HerionanTriangle { a: 4, b: 13, c: 15, area: 24, perimeter: 32 }
HerionanTriangle { a: 5, b: 12, c: 13, area: 30, perimeter: 30 }
HerionanTriangle { a: 9, b: 10, c: 17, area: 36, perimeter: 36 }
HerionanTriangle { a: 3, b: 25, c: 26, area: 36, perimeter: 54 }
HerionanTriangle { a: 7, b: 15, c: 20, area: 42, perimeter: 42 }
HerionanTriangle { a: 10, b: 13, c: 13, area: 60, perimeter: 36 }
HerionanTriangle { a: 8, b: 15, c: 17, area: 60, perimeter: 40 }
 
All with area 210 subject to the previous ordering:
HerionanTriangle { a: 17, b: 25, c: 28, area: 210, perimeter: 70 }
HerionanTriangle { a: 20, b: 21, c: 29, area: 210, perimeter: 70 }
HerionanTriangle { a: 12, b: 35, c: 37, area: 210, perimeter: 84 }
HerionanTriangle { a: 17, b: 28, c: 39, area: 210, perimeter: 84 }
HerionanTriangle { a: 7, b: 65, c: 68, area: 210, perimeter: 140 }
HerionanTriangle { a: 3, b: 148, c: 149, area: 210, perimeter: 300 }
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object Heron extends scala.collection.mutable.MutableList[Seq[Int]] with App {
private final val n = 200
for (c <- 1 to n; b <- 1 to c; a <- 1 to b if gcd(gcd(a, b), c) == 1) {
Line 2,467 ⟶ 4,699:
private final val header = "\nSides Perimeter Area"
private def format: Seq[Int] => String = "\n%3d x %3d x %3d %5d %10d".format
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">class Triangle(a, b, c) {
 
has (sides, perimeter, area)
 
method init {
sides = [a, b, c].sort
perimeter = [a, b, c].sum
var s = (perimeter / 2)
area = sqrt(s * (s - a) * (s - b) * (s - c))
}
 
method is_valid(a,b,c) {
var (short, middle, long) = [a, b, c].sort...;
(short + middle) > long
}
 
method is_heronian {
area == area.to_i
}
 
method <=>(other) {
[area, perimeter, sides] <=> [other.area, other.perimeter, other.sides]
}
 
method to_s {
"%-11s%6d%8.1f" % (sides.join('x'), perimeter, area)
}
}
 
var (max, area) = (200, 210)
var prim_triangles = []
 
for a in (1..max) {
for b in (a..max) {
for c in (b..max) {
next if (Math.gcd(a, b, c) > 1)
prim_triangles << Triangle(a, b, c) if Triangle.is_valid(a, b, c)
}
}
}
 
var sorted = prim_triangles.grep{.is_heronian}.sort
 
say "Primitive heronian triangles with sides upto #{max}: #{sorted.size}"
say "\nsides perim. area"
say sorted.first(10).join("\n")
say "\nTriangles with an area of: #{area}"
sorted.each{|tr| say tr if (tr.area == area)}</syntaxhighlight>
{{out}}
<pre>
Primitive heronian triangles with sides upto 200: 517
 
sides perim. area
3x4x5 12 6.0
5x5x6 16 12.0
5x5x8 18 12.0
4x13x15 32 24.0
5x12x13 30 30.0
9x10x17 36 36.0
3x25x26 54 36.0
7x15x20 42 42.0
10x13x13 36 60.0
8x15x17 40 60.0
 
Triangles with an area of: 210
17x25x28 70 210.0
20x21x29 70 210.0
12x35x37 84 210.0
17x28x39 84 210.0
7x65x68 140 210.0
3x148x149 300 210.0
</pre>
 
=={{header|Smalltalk}}==
Works with Squeak 5.x
<syntaxhighlight lang="smalltalk">perimeter := [:triangle | triangle reduce: #+].
 
squaredArea := [:triangle |
| s |
s := (perimeter value: triangle) / 2.
triangle inject: s into: [:a2 :edge | s - edge * a2]].
 
isPrimitive := [:triangle | (triangle reduce: #gcd:) = 1].
 
isHeronian := [:triangle | (squaredArea value: triangle) sqrt isInteger].
 
heroGenerator := Generator on: [:generator |
1 to: 200 do: [:a |
a to: 200 do: [:b |
b to: (a+b-1 min: 200) do: [:c |
| triangle |
triangle := {a. b. c.}.
((isPrimitive value: triangle) and: [isHeronian value: triangle])
ifTrue: [generator nextPut: triangle]]]]].
 
heronians := heroGenerator contents.
sorter := squaredArea ascending , perimeter ascending , #third ascending , #second ascending , #first ascending.
sorted := heronians sorted: sorter.
area210 := sorted select: [:triangle | (squaredArea value: triangle) = 210 squared].
 
header := [:title |
Transcript cr; cr; nextPutAll: title; cr.
#(peri area a b c) do: [:s | Transcript nextPutAll: s; tab]].
tabulate := [:t |
Transcript cr.
Transcript print: (perimeter value: t); tab.
Transcript print: (squaredArea value: t) sqrt.
t do: [:edge | Transcript tab; print: edge].].
 
Transcript cr; print: heronians size; nextPutAll: ' heronians triangles of side <= 200 where found'.
header value: 'first 10 sorted by area, then perimeter, the largest side'.
(sorted first: 10) do: tabulate.
header value: 'heronians of area 210'.
area210 do: tabulate.
 
Transcript flush.</syntaxhighlight>
{{out}}
<pre>
517 heronians triangles of side <= 200 where found
 
first 10 sorted by area, then perimeter, the largest side
peri area a b c
12 6 3 4 5
16 12 5 5 6
18 12 5 5 8
32 24 4 13 15
30 30 5 12 13
36 36 9 10 17
54 36 3 25 26
42 42 7 15 20
36 60 10 13 13
40 60 8 15 17
 
heronians of area 210
peri area a b c
70 210 17 25 28
70 210 20 21 29
84 210 12 35 37
84 210 17 28 39
140 210 7 65 68
300 210 3 148 149
</pre>
 
=={{header|SPL}}==
<syntaxhighlight lang="spl">h,t = getem(200)
#.sort(h,4,5,1,2,3)
#.output("There are ",t," Heronian triangles")
#.output(" a b c area perimeter")
#.output("----- ----- ----- ------ ---------")
> i, 1..#.min(10,t)
print(h,i)
<
#.output(#.str("...",">34<"))
> i, 1..t
? h[4,i]=210, print(h,i)
<
print(h,i)=
#.output(#.str(h[1,i],">4>")," ",#.str(h[2,i],">4>")," ",#.str(h[3,i],">4>")," ",#.str(h[4,i],">5>")," ",#.str(h[5,i],">8>"))
.
getem(n)=
> a, 1..n
> b, #.upper((a+1)/2)..a
> c, a-b+1..b
x = ((a+b+c)*(a+b-c)*(a-b+c)*(b-a+c))^0.5
>> x%1 | #.gcd(a,b,c)>1
t += 1
h[1,t],h[2,t],h[3,t] = #.sort(a,b,c)
h[4,t],h[5,t] = heron(a,b,c)
<
<
<
<= h,t
.
heron(a,b,c)=
s = (a+b+c)/2
<= (s*(s-a)*(s-b)*(s-c))^0.5, s*2
.</syntaxhighlight>
{{out}}
<pre>
There are 517 Heronian triangles
a b c area perimeter
----- ----- ----- ------ ---------
3 4 5 6 12
5 5 6 12 16
5 5 8 12 18
4 13 15 24 32
5 12 13 30 30
9 10 17 36 36
3 25 26 36 54
7 15 20 42 42
10 13 13 60 36
8 15 17 60 40
...
17 25 28 210 70
20 21 29 210 70
12 35 37 210 84
17 28 39 210 84
7 65 68 210 140
3 148 149 210 300
</pre>
 
=={{header|Swift}}==
Works with Swift 1.2
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
typealias PrimitiveHeronianTriangle = (s1:Int, s2:Int, s3:Int, p:Int, a:Int)
Line 2,524 ⟶ 4,959:
for t in triangles[0...9] {
println("\(t.s1)\t\(t.s2)\t\(t.s3)\t\t\(t.p)\t\t\(t.a)")
}</langsyntaxhighlight>
 
{{out}}
Line 2,547 ⟶ 4,982:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">
if {[info commands let] eq ""} {
 
Line 2,639 ⟶ 5,074:
sqlite3 db :memory:
main db
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,665 ⟶ 5,100:
(3, 148, 149) perimiter = 300; area = 210
</pre>
 
=={{header|VBA}}==
{{trans|Phix}}<syntaxhighlight lang="vb">Function heroArea(a As Integer, b As Integer, c As Integer) As Double
s = (a + b + c) / 2
On Error GoTo Err
heroArea = Sqr(s * (s - a) * (s - b) * (s - c))
Exit Function
Err:
heroArea = -1
End Function
Function hero(h As Double) As Boolean
hero = (h - Int(h) = 0) And h > 0
End Function
Public Sub main()
Dim list() As Variant, items As Integer
Dim a As Integer, b As Integer, c As Integer
Dim hArea As Double
Dim tries As Long
For a = 1 To 200
For b = 1 To a
For c = 1 To b
tries = tries + 1
If gcd(gcd(a, b), c) = 1 Then
hArea = heroArea(a, b, c)
If hero(hArea) Then
ReDim Preserve list(items)
list(items) = Array(CStr(hArea), CStr(a + b + c), CStr(a), CStr(b), CStr(c))
items = items + 1
End If
End If
Next c
Next b
Next a
list = sort(list)
Debug.Print "Primitive Heronian triangles with sides up to 200:"; UBound(list) + 1; "(of"; tries; "tested)"
Debug.Print
Debug.Print "First 10 ordered by area/perimeter/sides:"
Debug.Print "area perimeter sides"
For i = 0 To 9
Debug.Print Format(list(i)(0), "@@@"), Format(list(i)(1), "@@@"),
Debug.Print list(i)(2); "x"; list(i)(3); "x"; list(i)(4)
Next i
Debug.Print
Debug.Print "area = 210:"
Debug.Print "area perimeter sides"
For i = 0 To UBound(list)
If Val(list(i)(0)) = 210 Then
Debug.Print Format(list(i)(0), "@@@"), Format(list(i)(1), "@@@"),
Debug.Print list(i)(2); "x"; list(i)(3); "x"; list(i)(4)
End If
Next i
End Sub</syntaxhighlight>{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517 (of 1353400 tested)
 
First 10 ordered by area/perimeter/sides:
area perimeter sides
6 12 5x4x3
12 16 6x5x5
12 18 8x5x5
24 32 15x13x4
30 30 13x12x5
36 36 17x10x9
36 54 26x25x3
42 42 20x15x7
60 36 13x13x10
60 40 17x15x8
 
area = 210:
area perimeter sides
210 70 28x25x17
210 70 29x21x20
210 84 37x35x12
210 84 39x28x17
210 140 68x65x7
210 300 149x148x3</pre>
 
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-sort}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./math" for Int, Nums
import "./sort" for Sort
import "./fmt" for Fmt
 
var isInteger = Fn.new { |n| n is Num && n.isInteger }
 
var primHeronian = Fn.new { |a, b, c|
if (!(isInteger.call(a) && isInteger.call(b) && isInteger.call(c))) return [false, 0, 0]
if (Int.gcd(Int.gcd(a, b), c) != 1) return [false, 0, 0]
var p = a + b + c
var s = p / 2
var A = (s * (s - a) * (s - b) * (s - c)).sqrt
if (A > 0 && isInteger.call(A)) return [true, A, p]
return [false, 0, 0]
}
 
var ph = []
for (a in 1..200) {
for (b in a..200) {
for (c in b..200) {
var res = primHeronian.call(a, b, c)
if (res[0]) {
var sides = [a, b, c]
ph.add([sides, res[1], res[2], Nums.max(sides)])
}
}
}
}
System.print("There are %(ph.count) primitive Heronian trangles with sides <= 200.")
 
var cmp = Fn.new { |e1, e2|
if (e1[1] != e2[1]) return (e1[1] - e2[1]).sign
if (e1[2] != e2[2]) return (e1[2] - e2[2]).sign
return (e1[3] - e2[3]).sign
}
Sort.quick(ph, 0, ph.count-1, cmp)
System.print("\nThe first 10 such triangles in sorted order are:")
System.print(" Sides Area Perimeter Max Side")
for (t in ph.take(10)) {
var sides = Fmt.swrite("$2d x $2d x $2d", t[0][0], t[0][1], t[0][2])
Fmt.print("$-14s $2d $2d $2d", sides, t[1], t[2], t[3])
}
 
System.print("\nThe triangles in the previously sorted order with an area of 210 are:")
System.print(" Sides Area Perimeter Max Side")
for (t in ph.where { |e| e[1] == 210 }) {
var sides = Fmt.swrite("$2d x $3d x $3d", t[0][0], t[0][1], t[0][2])
Fmt.print("$-14s $3d $3d $3d", sides, t[1], t[2], t[3])
}</syntaxhighlight>
 
{{out}}
<pre>
There are 517 primitive Heronian trangles with sides <= 200.
 
The first 10 such triangles in sorted order are:
Sides Area Perimeter Max Side
3 x 4 x 5 6 12 5
5 x 5 x 6 12 16 6
5 x 5 x 8 12 18 8
4 x 13 x 15 24 32 15
5 x 12 x 13 30 30 13
9 x 10 x 17 36 36 17
3 x 25 x 26 36 54 26
7 x 15 x 20 42 42 20
10 x 13 x 13 60 36 13
8 x 15 x 17 60 40 17
 
The triangles in the previously sorted order with an area of 210 are:
Sides Area Perimeter Max Side
17 x 25 x 28 210 70 28
20 x 21 x 29 210 70 29
12 x 35 x 37 210 84 37
17 x 28 x 39 210 84 39
7 x 65 x 68 210 140 68
3 x 148 x 149 210 300 149
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">include xpllib; \for Min, GCD, StrSort, StrNCmp, and Print
 
func Hero(A, B, C); \Return area squared of triangle with sides A, B, C
int A, B, C, S;
[S:= (A+B+C)/2;
if rem(0) = 1 then return 0; \return 0 if area is not an integer
return S*(S-A)*(S-B)*(S-C);
];
 
func Heronian(A, B, C); \Return area of triangle if sides and area are integers
int A, B, C, Area2, Area;
[Area2:= Hero(A, B, C);
Area:= sqrt(Area2);
return if Area*Area = Area2 then Area else 0;
];
 
def MaxSide = 200;
int A, B, C, Area, Count, I, J, K;
char Array(1000, 5*5);
[Format(5, 0);
Count:= 0;
for A:= 1 to MaxSide do
for B:= A to MaxSide do
for C:= B to Min(A+B-1, MaxSide) do
if GCD(GCD(B,C), A) = 1 then
[Area:= Heronian(A, B, C);
if Area > 0 then
[OpenO(8);
RlOut(8, float(Area));
RlOut(8, float(A+B+C));
RlOut(8, float(C));
RlOut(8, float(B));
RlOut(8, float(A));
OpenI(8);
for I:= 0 to 25-1 do Array(Count,I):= ChIn(8);
Count:= Count+1;
];
];
Print("Count = %d\n", Count);
StrSort(Array, Count);
Print(" A B C Perim Area\n");
for I:= 0 to 10-1 do
[for J:= 4 downto 0 do
Print("%5.5s", @Array(I, J*5+K));
Print("\n");
];
Print("\n");
for I:= 0 to Count-1 do
if StrNCmp(" 210", @Array(I,0), 5) = 0 then
[for J:= 4 downto 0 do
Print("%5.5s", @Array(I, J*5+K));
Print("\n");
];
]</syntaxhighlight>
{{out}}
<pre>
Count = 517
A B C Perim Area
3 4 5 12 6
5 5 6 16 12
5 5 8 18 12
4 13 15 32 24
5 12 13 30 30
9 10 17 36 36
3 25 26 54 36
7 15 20 42 42
10 13 13 36 60
8 15 17 40 60
 
17 25 28 70 210
20 21 29 70 210
12 35 37 84 210
17 28 39 84 210
7 65 68 140 210
3 148 149 300 210
</pre>
 
=={{header|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">fcn hero(a,b,c){ //--> area (float)
s,a2:=(a + b + c).toFloat()/2, s*(s - a)*(s - b)*(s - c);
(a2 > 0) and a2.sqrt() or 0.0
Line 2,674 ⟶ 5,347:
A:=hero(a,b,c);
(A>0) and A.modf()[1].closeTo(0.0,1.0e-6) and A //--> area or False
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">const MAX_SIDE=200;
heros:=Sink(List);
foreach a,b,c in ([1..MAX_SIDE],[a..MAX_SIDE],[b..MAX_SIDE]){
Line 2,696 ⟶ 5,369:
println("Area Perimeter Sides");
heros.filter(fcn([(h,_)]){ h==210 })
.pump(fcn(phabc){ "%3s %8d %3dx%dx%d".fmt(phabc.xplode()).println() });</langsyntaxhighlight>
{{out}}
<pre>
9,485

edits