Heronian triangles: Difference between revisions
Content deleted Content added
J |
jq |
||
Line 139: | Line 139: | ||
7 65 68 _ 210 140 |
7 65 68 _ 210 140 |
||
3 148 149 _ 210 300</lang> |
3 148 149 _ 210 300</lang> |
||
=={{header|jq}}== |
|||
{{works with|jq|1.4}} |
|||
<lang jq># input should be an array of the lengths of the sides |
|||
def hero: |
|||
(add/2) as $s |
|||
| ($s*($s - .[0])*($s - .[1])*($s - .[2])) as $a2 |
|||
| if $a2 > 0 then ($a2 | sqrt) else 0 end; |
|||
def is_heronian: |
|||
hero as $h |
|||
| $h > 0 and ($h|floor) == $h; |
|||
def gcd3(x; y; z): |
|||
# subfunction expects [a,b] as input |
|||
def rgcd: |
|||
if .[1] == 0 then .[0] |
|||
else [.[1], .[0] % .[1]] | rgcd |
|||
end; |
|||
[ ([x,y] | rgcd), z ] | rgcd; |
|||
def task(maxside): |
|||
def rjust(width): tostring | " " * (width - length) + .; |
|||
[ range(1; maxside+1) as $c |
|||
| range(1; $c+1) as $b |
|||
| range(1; $b+1) as $a |
|||
| if ($a + $b) > $c and gcd3($a; $b; $c) == 1 |
|||
then [$a,$b,$c] | if is_heronian then . else empty end |
|||
else empty |
|||
end ] |
|||
# sort by increasing area, perimeter, then sides |
|||
| sort_by( [ hero, add, .[2] ] ) |
|||
| "The number of primitive Heronian triangles with sides up to \(maxside): \(length)", |
|||
"The first ten when ordered by increasing area, then perimeter, then maximum sides:", |
|||
" perimeter area", |
|||
(.[0:10][] | "\(rjust(11)) \(add | rjust(3)) \(hero | rjust(4))" ), |
|||
"All those with area 210, ordered as previously:", |
|||
" perimeter area", |
|||
( .[] | select( hero == 210 ) | "\(rjust(11)) \(add|rjust(3)) \(hero|rjust(4))" ) ; |
|||
task(200)</lang> |
|||
{{out}} |
|||
<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: |
|||
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 |
|||
All those with area 210, ordered as previously: |
|||
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</lang> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |