Heronian triangles: Difference between revisions
Actually do the changes.
Drkameleon (talk | contribs) (added Arturo) |
(Actually do the changes.) |
||
Line 3,123:
=={{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.
func `$` (t: HeronianTriangle): string =▼
func max(a, b, c: int): int = max(a, max(b, c))▼
func gcd(a, b, c: int): int = gcd(a, gcd(b, c))▼
func cmp(x, y: HeronianTriangle): int =
## Compare two Heronian triangles.
result = cmp(x.area, y.area)▼
if result == 0:▼
result = cmp(x.p, y.p)▼
if result == 0:▼
result = cmp(max(x.a, x.b, x.c), max(y.a, y.b, y.c))▼
## Return the representation of a Heronian triangle.
fmt"{t.a:3d}, {t.b:3d}, {t.c:3d} {t.p:7d} {t.area:8d}"
func hero(a, b, c: int): float =
## Return the area of a triangle using Hero's formula.
let s = (a + b + c) / 2
result = sqrt(s * (s - a) * (s - b) * (s - c))
Line 3,136 ⟶ 3,151:
func isHeronianTriangle(x: float): bool = x > 0 and ceil(x) == x
# func gcd(x, y: int): int =
# var
# (dividend, divisor) = if x > y: (x, y) else: (y, x)
# remainder = dividend mod divisor
# while remainder != 0:
# dividend = divisor
# divisor = remainder
# remainder = dividend mod divisor
# result = divisor
▲func max(a, b, c: int): int = max(a, max(b, c))
▲func gcd(a, b, c: int): int = gcd(a, gcd(b, c))
const Header = " Sides Perimeter Area\n------------- --------- ----"
Line 3,159 ⟶ 3,171:
for a in 1..b:
let area = hero(a, b, c)
if
let t: HeronianTriangle = (a, b, c, a + b + c, area.toInt)
list.add
list.sort(cmp)
echo "Number of Heronian triangles: ", list.len
▲list.sort do (x, y: HeronianTriangle) -> int:
▲ result = cmp(x.area, y.area)
▲ if result == 0:
▲ result = cmp(x.p, y.p)
▲ if result == 0:
▲ result = cmp(max(x.a, x.b, x.c), max(y.a, y.b, y.c))
echo "\nOrdered list of first ten Heronian triangles:"
|