Heronian triangles: Difference between revisions
m
syntax highlighting fixup automation
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 39:
{{trans|Python}}
<
L v != 0
(u, v) = (v, u % v)
Line 70:
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"))</
{{out}}
Line 98:
=={{header|Ada}}==
<
with Ada.Finalization;
with Ada.Text_IO; use Ada.Text_IO;
Line 228:
end loop;
end;
end Heronian;</
{{out}}
<pre> 517 heronian triangles found :
Line 257:
=={{header|ALGOL 68}}==
{{Trans|Lua}}
<
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 #
Line 339:
OD
END
END</
{{out}}
<pre>
Line 369:
=={{header|ALGOL W}}==
{{Trans|Lua}}
<
% record to hold details of a Heronian triangle %
record Heronian ( integer a, b, c, area, perimeter );
Line 465:
end
end
end.</
{{out}}
<pre>
Line 498:
{{Trans|JavaScript}}
<
-- HERONIAN TRIANGLES --------------------------------------------------------
Line 774:
((ca's NSString's stringWithString:(str))'s ¬
capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toTitle</
{{Out}}
<pre>Number of triangles found (with sides <= 200): 517
Line 803:
=={{header|AutoHotkey}}==
<
obj :=[]
loop, % MaxSide {
Line 821:
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
}</
Examples:<
loop, parse, res, `n, `r
{
Line 837:
. "`nResults for Area = 210:"
. "`n" "Area`tPerimeter`tSides`n" res3
return</
Outputs:<pre>517 results found
Line 867:
----
'''IMPORTANT''': This is a C99 compatible implementation. May result in errors on earlier compilers.
<syntaxhighlight lang="c">
#include<stdlib.h>
#include<stdio.h>
Line 988:
return 0;
}
</syntaxhighlight>
Invocation and output :
<pre>
Line 1,018:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
Line 1,075:
}
}
}</
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
Line 1,103:
=={{header|C++}}==
{{Works with|C++11}}
<
#include <cmath>
#include <iostream>
Line 1,188:
std::cout << area(*it) << '\t' << perimeter(*it) << "\t\t" <<
it->a << 'x' << it->b << 'x' << it->c << '\n';
}</
{{out}}
<pre>There are 517 primitive Heronian triangles with sides up to 200
Line 1,216:
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<
s = (a + b + c) / 2
Math.sqrt s * (s - a) * (s - b) * (s - c)
Line 1,262:
for i in list
if i[4] == 210
console.log i[0..2].join(' x ') + ', p = ' + i[3]</
{{out}}
<pre>primitive Heronian triangles with sides up to 200: 517
Line 1,287:
=={{header|D}}==
{{trans|Python}}
<
double hero(in uint a, in uint b, in uint c) pure nothrow @safe @nogc {
Line 1,331:
"\nAll with area 210 subject to the previous ordering:".writeln;
showTriangles(h.filter!(t => t[].hero == 210));
}</
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 1,360:
=={{header|EchoLisp}}==
<
;; returns quintuple (A s a b c)
;; or #f if not hero
Line 1,386:
(define (print-laurels H)
(writeln '🌿🌿 (length H) 'heroes '🌿🌿))
</syntaxhighlight>
{{out}}
<pre>(define H (heroes))
Line 1,416:
=={{header|Elixir}}==
<
def triangle?(a,b,c) when a+b <= c, do: false
def triangle?(a,b,c) do
Line 1,451:
|> Enum.each(fn {a, b, c} ->
IO.puts "#{a}\t#{b}\t#{c}\t#{a+b+c}\t#{area_size}"
end)</
{{out}}
Line 1,476:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM HERON
Line 1,544:
END FOR
END PROGRAM
</syntaxhighlight>
<pre>Number of triangles: 517
3 4 5 12 6
Line 1,565:
=={{header|Factor}}==
<
combinators.short-circuit formatting io kernel locals math
math.functions math.order math.parser math.ranges mirrors qw
Line 1,626:
[ first10 nl ] [ area210= ] bi ;
MAIN: main</
{{out}}
<pre>
Line 1,658:
=={{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">
MODULE GREEK MATHEMATICIANS !Two millenia back and more.
CONTAINS
Line 1,766:
END DO !Just thump through the lot.
END
</syntaxhighlight>
{{out}}
Line 1,791:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,937:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>There are 517 Heronian triangles with sides <= 200
Line 1,969:
=={{header|FutureBasic}}==
<
include "ConsoleWindow"
Line 2,056:
end if
next
</syntaxhighlight>
Output:
Line 2,087:
=={{header|Go}}==
<
import (
Line 2,156:
}
}
}</
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
Line 2,183:
=={{header|Haskell}}==
<
import Data.Maybe
import Data.Ord
Line 2,245:
mapM_ printTri $ take 10 tris
putStrLn ""
mapM_ printTri $ filter ((== 210) . fifth) tris</
{{out}}
<pre>Heronian triangles found: 517
Line 2,272:
'''Hero's formula Implementation'''
<
b=: 1&{"1
c=: 2&{"1
Line 2,278:
area=: 2 %: s*(s-a)*(s-b)*(s-c) NB. Hero's formula
perim=: +/"1
isPrimHero=: (0&~: * (= <.@:+))@area * 1 = a +. b +. c</
We exclude triangles with zero area, triangles with complex area, non-integer area, and triangles whose sides share a common integer multiple.
Line 2,286:
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:
<
s=: -:@:perim
area=: [: %: s * [: */"1 s - ] NB. Hero's formula
isNonZeroInt=: 0&~: *. (= <.@:+)
isPrimHero=: isNonZeroInt@area *. 1 = +./&.|:</
'''Required examples'''
<
HeroTri=: (#~ isPrimHero) Tri NB. all primitive Heronian triangles with sides <= 200
Line 2,320:
17 28 39 _ 84 210
7 65 68 _ 140 210
3 148 149 _ 300 210</
=={{header|Java}}==
<
public class Heron {
Line 2,399:
}
}
}</
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
Line 2,429:
===Imperative===
<syntaxhighlight lang="javascript">
window.onload = function(){
var list = [];
Line 2,480:
}
}
</syntaxhighlight>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 2,517:
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.
<
var chain = function (xs, f) { // Monadic bind/chain
Line 2,598:
) + '\n\n';
})(200);</
{{out}}
Line 2,653:
=={{header|jq}}==
{{works with|jq|1.4}}
<
def hero:
(add/2) as $s
Line 2,692:
( .[] | select( hero == 210 ) | "\(rjust(11)) \(add|rjust(3)) \(hero|rjust(4))" ) ;
task(200)</
{{out}}
<
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 2,715:
[17,28,39] 84 210
[7,65,68] 140 210
[3,148,149] 300 210</
=={{header|Julia}}==
Line 2,721:
'''Types and Functions'''
<syntaxhighlight lang="julia">
type IntegerTriangle{T<:Integer}
a::T
Line 2,748:
σ^2 == t
end
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
slim = 200
Line 2,785:
println(@sprintf "%6d %3d %3d %4d %4d" t.a t.b t.c t.σ t.p)
end
</syntaxhighlight>
{{out}}
Line 2,814:
=={{header|Kotlin}}==
{{trans|Scala}}
<
object Heron {
Line 2,877:
}
fun main(args: Array<String>) = Heron.run()</
{{out}}
<pre>Number of primitive Heronian triangles with sides up to 200: 517
Line 2,904:
=={{header|Lua}}==
<
local function tryHt( a, b, c )
local result
Line 2,964:
local t = ht[ htPos ];
if t.area == 210 then htPrint( t ) end
end</
{{out}}
<pre>
Line 2,993:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Heron[a_, b_, c_] := With[{s = (a + b + c)/2}, Sqrt[s (s - a) (s - b) (s - c)]]
PrintTemporary[Dynamic[{a, b, c}]];
Line 3,015:
results // Length
Take[results, 10] // Dataset
Select[results, #["Area"] == 210 &] // Dataset</
{{out}}
<pre>517
Line 3,040:
=={{header|Nim}}==
<
type HeronianTriangle = tuple[a, b, c: int; p: int; area: int]
Line 3,096:
echo Header
for t in list.filterIt(it.area == 210): echo t
</syntaxhighlight>
{{out}}
<pre>Number of Heronian triangles: 517
Line 3,126:
=={{header|ooRexx}}==
Derived from REXX with some changes
<
Call time 'R'
Numeric Digits 12
Line 3,263:
::requires rxmath library
::routine sqrt
Return rxCalcSqrt(arg(1),14)</
{{out}}
<pre>517 primitive Heronian triangles found with side length up to 200 (inclusive).
Line 3,290:
=={{header|PARI/GP}}==
<
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 3,300:
vecsort(u, (a,b)->Heron(a)-Heron(b))
vecsort(u, (a,b)->vecsum(a)-vecsum(b))
vecsort(u, 3) \\ shortcut: order by third component</
{{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 3,311:
=={{header|Pascal}}==
{{Trans|Lua}}
<
type
(* record to hold details of a Heronian triangle *)
Line 3,411:
if t^.area = 210 then htPrint( t )
end
end.</
{{out}}
<pre>
Line 3,441:
=={{header|Perl}}==
{{trans|Raku}}
<
use warnings;
use List::Util qw(max);
Line 3,503:
}
&main();</
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 3,528:
=={{header|Phix}}==
<!--<
<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>
<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>
Line 3,567:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,596:
=={{header|PowerShell}}==
<
function Get-Gcd($a, $b){
if($a -ge $b){
Line 3,644:
}
}
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
Primitive Heronian triangles with sides up to 200: 517
Line 3,670:
7 65 68 140 210
3 148 149 300 210
</syntaxhighlight>
=={{header|Python}}==
<
from math import gcd, sqrt
Line 3,718:
% (sides, sum(sides), hero(*sides)) for sides in h
if hero(*sides) == 210))
</syntaxhighlight>
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 3,746:
Mostly adopted from Python implementation:
<syntaxhighlight lang="r">
area <- function(a, b, c) {
s = (a + b + c) / 2
Line 3,783:
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>
{{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 3,799:
[8,] 8 15 17 40 60
[9,] 7 15 20 42 42
[10,] 13 14 15 42 84</
=={{header|Racket}}==
<syntaxhighlight lang="text">#lang at-exp racket
(require data/order scribble/html)
Line 3,847:
@; Show a similar ordered table for those triangles with area = 210
@(triangles->table (tri-sort (filter (λ(t) (eq? 210 (car t))) ts)))
}))</
This program generates HTML, so the output is inline with the page, not in a <code><pre></code> block.
Line 3,880:
(formerly Perl 6)
{{works with|Rakudo|2018.09}}
<syntaxhighlight lang="raku"
my $s = ($a + $b + $c) / 2;
($s * ($s - $a) * ($s - $b) * ($s - $c)).sqrt;
Line 3,922:
say "\nArea $witharea:";
show @h.grep: *[0] == $witharea;
}</
{{out}}
<pre>Primitive Heronian triangles with sides up to 200: 517
Line 3,978:
This REXX version doesn't need to explicitly sort the triangles as they are listed in the proper order.
<
parse arg N first area . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 200 /*Not specified? Then use the default.*/
Line 4,030:
end /*k*/
end /*j*/ /* [↑] use the known perimeters. */
end /*i*/; return /* [↑] show any found triangles. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 4,065:
It is about eight times faster than the 1<sup>st</sup> REXX version.
<
parse arg N first area . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 200 /*Not specified? Then use the default.*/
Line 4,110:
end /*k*/
end /*j*/ /* [↑] use the known perimeters. */
end /*i*/; return /* [↑] show any found triangles. */</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br>
=={{header|Ring}}==
<
# Project : Heronian triangles
Line 4,155:
end
return gcd
</syntaxhighlight>
Output:
<pre>
Line 4,183:
=={{header|Ruby}}==
<
def self.valid?(a,b,c) # class method
short, middle, long = [a, b, c].sort
Line 4,228:
puts sorted.first(10).map(&:to_s)
puts "\nTriangles with an area of: #{area}"
sorted.each{|tr| puts tr if tr.area == area}</
{{out}}
<pre>
Line 4,255:
=={{header|Rust}}==
<
use num_integer::Integer;
use std::{f64, usize};
Line 4,323:
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,350:
=={{header|Scala}}==
<
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 4,384:
private final val header = "\nSides Perimeter Area"
private def format: Seq[Int] => String = "\n%3d x %3d x %3d %5d %10d".format
}</
=={{header|Sidef}}==
{{trans|Ruby}}
<
has (sides, perimeter, area)
Line 4,435:
say sorted.first(10).join("\n")
say "\nTriangles with an area of: #{area}"
sorted.each{|tr| say tr if (tr.area == area)}</
{{out}}
<pre>
Line 4,463:
=={{header|Smalltalk}}==
Works with Squeak 5.x
<
squaredArea := [:triangle |
Line 4,503:
area210 do: tabulate.
Transcript flush.</
{{out}}
<pre>
Line 4,532:
=={{header|SPL}}==
<
#.sort(h,4,5,1,2,3)
#.output("There are ",t," Heronian triangles")
Line 4,564:
s = (a+b+c)/2
<= (s*(s-a)*(s-b)*(s-c))^0.5, s*2
.</
{{out}}
<pre>
Line 4,591:
=={{header|Swift}}==
Works with Swift 1.2
<
typealias PrimitiveHeronianTriangle = (s1:Int, s2:Int, s3:Int, p:Int, a:Int)
Line 4,644:
for t in triangles[0...9] {
println("\(t.s1)\t\(t.s2)\t\(t.s3)\t\t\(t.p)\t\t\(t.a)")
}</
{{out}}
Line 4,667:
=={{header|Tcl}}==
<
if {[info commands let] eq ""} {
Line 4,759:
sqlite3 db :memory:
main db
</syntaxhighlight>
{{out}}
<pre>
Line 4,787:
=={{header|VBA}}==
{{trans|Phix}}<
s = (a + b + c) / 2
On Error GoTo Err
Line 4,838:
End If
Next i
End Sub</
<pre>Primitive Heronian triangles with sides up to 200: 517 (of 1353400 tested)
Line 4,867:
{{libheader|Wren-sort}}
{{libheader|Wren-fmt}}
<
import "/sort" for Sort
import "/fmt" for Fmt
Line 4,916:
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])
}</
{{out}}
Line 4,947:
=={{header|zkl}}==
{{trans|Python}}
<
s,a2:=(a + b + c).toFloat()/2, s*(s - a)*(s - b)*(s - c);
(a2 > 0) and a2.sqrt() or 0.0
Line 4,954:
A:=hero(a,b,c);
(A>0) and A.modf()[1].closeTo(0.0,1.0e-6) and A //--> area or False
}</
<
heros:=Sink(List);
foreach a,b,c in ([1..MAX_SIDE],[a..MAX_SIDE],[b..MAX_SIDE]){
Line 4,976:
println("Area Perimeter Sides");
heros.filter(fcn([(h,_)]){ h==210 })
.pump(fcn(phabc){ "%3s %8d %3dx%dx%d".fmt(phabc.xplode()).println() });</
{{out}}
<pre>
|