Pythagorean triples: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 28:
{{trans|D}}
<
F countTriples(Int64 =x, =y, =z)
Line 57:
nTriples = nPrimitives = 0
countTriples(3, 4, 5)
print(‘Up to #11: #11 triples, #9 primitives.’.format(limit, nTriples, nPrimitives))</
{{out}}
Line 73:
=={{header|360 Assembly}}==
{{trans|Perl}}
<
PYTHTRI CSECT
USING PYTHTRI,R13 base register
Line 199:
ISQRTSA DS 8A context store
YREGS
END PYTHTRI</
{{out}}
<pre>
Line 211:
=={{header|Action!}}==
<
DEFINE ENTRY_SIZE="3"
TYPE TRIPLE=[BYTE a,b,c]
Line 318:
PrintF("%E%E%E%B of them are primitive:%E%E",res2.count)
PrintTriples(res2)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pythagorean_triples.png Screenshot from Atari 8-bit computer]
Line 336:
Translation of efficient method from C, see [[wp:Pythagorean_triple#Parent.2Fchild_relationships|the WP article]]. Compiles on gnat/gcc.
<
procedure Pythagorean_Triples is
Line 368:
Large_Natural'Image(P_Cnt) & " Primitives");
end loop;
end Pythagorean_Triples;</
Output:
Line 386:
Translation of BBC BASIC Program
<
110 !
120 PUBLIC NUMERIC U0(3,3), U1(3,3), U2(3,3), all, prim
Line 428:
500 NEXT i
510 LET SUM = temp
520 END FUNCTION</
=={{header|Arturo}}==
<
loop 1..50 'x [
loop 1..50 'y [
Line 452:
print ""
print [size primitive "of them are primitive:"]
print primitive</
{{out}}
Line 463:
=={{header|APL}}==
<syntaxhighlight lang="apl">
⍝ Determine whether given list of integers has GCD = 1
primitive←∧/1=2∨/⊢
Line 495:
perimeter_rule←{maxperimeter≥+/⍵}
res←perimeter_rule¨filter add_c¨sos_is_sq filter a_b_pairs
∇</
{{out}}
<pre>
Line 507:
=={{header|AutoHotkey}}==
<
SetBatchLines, -1
#SingleInstance, Force
Line 536:
Loop, 8
Msgbox % 10**A_Index ": " count_triples(10**A_Index)</
{{out}}
Line 549:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f PYTHAGOREAN_TRIPLES.AWK
# converted from Go
Line 573:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 590:
=={{header|BBC BASIC}}==
The built-in array arithmetic is very well suited to this task!
<
U0%() = 1, -2, 2, 2, -1, 2, 2, -2, 3
U1%() = 1, 2, 2, 2, 1, 2, 2, 2, 3
Line 616:
t%() = U2%() . i%()
PROCtri(t%(), mp%, all%, prim%)
ENDPROC</
'''Output:'''
<pre>
Line 631:
=={{header|Bracmat}}==
{{trans|C}}
<
total prim max-peri U
. (.(1,-2,2) (2,-1,2) (2,-2,3))
Line 684:
pythagoreanTriples$;
</syntaxhighlight>
Output (under Linux):
Line 699:
With very few changes we can get rid of the stack exhausting recursion. Instead of calling <code>new-tri</code> recursively, be push the triples to test onto a stack and return to the <code>Main</code> function. In the innermost loop we pop a triple from the stack and call <code>new-tri</code>. The memory overhead is only a few megabytes for a max perimeter of 100,000,000. On my Windows XP box the whole computation takes at least 15 minutes! Given enough time (and memory), the program can compute results for larger perimeters.
<
total prim max-peri U stack
. (.(1,-2,2) (2,-1,2) (2,-2,3))
Line 752:
);
pythagoreanTriples$;</
=={{header|C}}==
Sample implemention; naive method, patentedly won't scale to larger numbers, despite the attempt to optimize it. Calculating up to 10000 is already a test of patience.
<
#include <stdlib.h>
Line 802:
return 0;
}</
Efficient method, generating primitive triples only as described in [[wp:Pythagorean_triple#Parent.2Fchild_relationships|the same WP article]]:<
#include <stdlib.h>
#include <stdint.h>
Line 850:
}
return 0;
}</
Up to 100: 17 triples, 7 primitives.
Up to 1000: 325 triples, 70 primitives.
Line 857:
Up to 1000000: 808950 triples, 70229 primitives.
Up to 10000000: 9706567 triples, 702309 primitives.
Up to 100000000: 113236940 triples, 7023027 primitives.</
Same as above, but with loop unwound and third recursion eliminated:
<
#include <stdlib.h>
#include <stdint.h>
Line 910:
}
return 0;
}</
=={{header|C++}}==
<
#include <iostream>
#include <numeric>
Line 968:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 986:
Based on Ada example, which is a translation of efficient method from C, see [[wp:Pythagorean_triple#Parent.2Fchild_relationships|the WP article]].
<
namespace RosettaCode.CSharp
Line 1,025:
}
}
}</
Output:
Line 1,042:
for each pair ''(m,n)'' such that ''m>n>0'', ''m'' and ''n'' coprime and of opposite polarity (even/odd),
there is a primitive Pythagorean triple. It can be proven that the converse is true as well.
<
(defn pyth [peri]
Line 1,058:
(reduce (fn [[total prims] t] [(inc total), (if (first t) (inc prims) prims)])
[0 0]
ts))</
To handle really large perimeters, we can dispense with actually generating the triples and just calculate the counts:
<
(reduce (fn [[total prims] k] [(+ total k), (inc prims)]) [0 0]
(for [m (range 2 (Math/sqrt (/ peri 2)))
Line 1,067:
:while (<= p peri)
:when (= 1 (gcd m n))]
(quot peri p))))</
=={{header|CoffeeScript}}==
This algorithm scales linearly with the max perimeter. It uses two loops that are capped by the square root of the half-perimeter to examine/count provisional values of m and n, where m and n generate a, b, c, and p using simple number theory.
<
gcd = (x, y) ->
return x if y == 0
Line 1,106:
max_perim = Math.pow 10, 9 # takes under a minute
count_triples(max_perim)
</syntaxhighlight>
output
<pre>
Line 1,115:
=={{header|Common Lisp}}==
<
(loop for x in a collect
(loop for y in x
Line 1,131:
(format t "~a: ~a prim, ~a all~%" lim prim cnt)))
(loop for p from 2 do (count-tri (expt 10 p)))</
1000: 70 prim, 325 all
10000: 703 prim, 4858 all
Line 1,137:
1000000: 70229 prim, 808950 all
10000000: 702309 prim, 9706567 all
...</
=={{header|Crystal}}==
{{trans|Ruby}}
<
def initialize(limit = 0)
@limit = limit
Line 1,170:
p [perim, c.total, c.primitives]
perim *= 10
end</
output
Line 1,185:
===Lazy Functional Version===
With hints from the Haskell solution.
<
import std.stdio, std.range, std.algorithm, std.typecons, std.numeric;
Line 1,199:
writeln("Up to 100 there are ", xs.count, " triples, ",
xs.filter!q{ a[0] }.count, " are primitive.");
}</
{{out}}
<pre>Up to 100 there are 17 triples, 7 are primitive.</pre>
===Shorter Version===
<
pure nothrow @safe @nogc {
immutable l = a + b + c;
Line 1,220:
foreach (immutable p; 1 .. 9)
writeln(10 ^^ p, ' ', tri(10 ^^ p));
}</
{{out}}
<pre>10 [0, 0]
Line 1,234:
===Short SIMD Version===
With LDC compiler this is a little faster than the precedent version (remove @nogc to compile it with the current version of LDC compiler).
<
ulong2 tri(in ulong lim, in ulong a=3, in ulong b=4, in ulong c=5)
Line 1,251:
foreach (immutable p; 1 .. 9)
writeln(10 ^^ p, ' ', tri(10 ^^ p).array);
}</
The output is the same. Run-time (32 bit system): about 0.67 seconds with ldc2.
===Faster Version===
{{trans|C}}
<
alias Xuint = uint; // ulong if going over 1 billion.
Line 1,295:
limit, nTriples, nPrimitives);
}
}</
{{out}}
<pre>Up to 10: 0 triples, 0 primitives.
Line 1,344:
The number of primitive triples divided by the maximum perimeter seems to tend to a limit,
which looks very much like (ln 2)/pi^2 = 0.07023049277 (see especially the FreeBASIC output below).
<
[Pythagorean triples for Rosetta code.
Counts (1) all Pythagorean triples (2) primitive Pythagorean triples,
Line 1,558:
E 15 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
Line 1,571:
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,619:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,631:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def count_triples(limit), do: count_triples(limit,3,4,5)
Line 1,644:
list = for n <- 1..8, do: Enum.reduce(1..n, 1, fn(_,acc)->10*acc end)
Enum.each(list, fn n -> IO.inspect {n, RC.count_triples(n)} end)</
{{out}}
Line 1,660:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">%%
%% Pythagorian triples in Erlang, J.W. Luiten
%%
Line 1,704:
L = lists:seq(1, Max),
Answer = lists:map(fun(X) -> count_triples(X) end, L),
lists:foreach(fun(Result) -> display_result(Result) end, Answer).</
Output:
Line 1,722:
=={{header|ERRE}}==
<
BEGIN
Line 1,780:
PRINT PRINT("** End **")
END PROGRAM</
{{out}}
<pre>16:08:39
Line 1,802:
=={{header|Euphoria}}==
{{trans|D}}
<
sequence r
atom p
Line 1,822:
? tri(max_peri, {3, 4, 5})
max_peri *= 10
end while</
Output:
Line 1,837:
=={{header|F_Sharp|F#}}==
{{trans|OCaml}}
<
let rec iter t =
let d = n - t*t
Line 1,868:
printfn "For perimeters up to %d there are %d total and %d primitive" i s p;;
List.iter show [ 100; 1000; 10000; 100000; 1000000; 10000000; 100000000 ]</
{{out}}
<pre>For perimeters up to 100 there are 17 total and 7 primitive
Line 1,881:
Pretty slow (100 times slower than C)...
<
math.functions math.matrices math.ranges sequences ;
IN: rosettacode.pyth
Line 1,923:
"Up to %d: %d triples, %d primitives.\n" printf ;
: pyth ( -- )
8 [1,b] [ 10^ dup count-triplets pprint-triplet-count ] each ;</
<pre>Up to 10: 0 triples, 0 primitives.
Line 1,938:
<syntaxhighlight lang="forth ">
Line 2,111:
ok
</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{trans|C efficient method}}
<
implicit none
Line 2,161:
max_peri = max_peri * 10
end do
end program Pythagorean</
Output:<pre>Up to 10 0 triples 0 primitives
Up to 100 17 triples 7 primitives
Line 2,178:
===Version 1===
Normal version
<
' compile with: fbc -s console
Line 2,267:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>below triples primitive time
Line 2,288:
Attempt to make a faster version (about 20% faster)
<
' compile with: fbc -s console
Line 2,369:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>below triples primitive time
Line 2,395:
=={{header|Go}}==
<
import "fmt"
Line 2,419:
maxPeri, total, prim)
}
}</
Output:
<pre>
Line 2,437:
===Parent/Child Algorithm===
Solution:
<
BigInteger a, b, c
def getPerimeter() { this.with { a + b + c } }
Line 2,472:
}
}
}</
Test:
<
findPythagTriples().sort().each { perimeterLimit, result ->
def exponent = perimeterLimit.toString().size() - 1
printf ('a+b+c <= 10E%2d %9d %12d\n', exponent, result.primative, result.total)
}</
Output:
Line 2,496:
=={{header|Haskell}}==
<
pytr n =
filter
Line 2,519:
<> " are primitive."
where
xs = pytr 100</
{{Out}}
Line 2,525:
Or equivalently (desugaring the list comprehension down to nested concatMaps, and pruning back the search space a little):
<
pythagoreanTriplesBelow :: Int -> [[Int]]
Line 2,550:
( [id, filter (\[x, y, _] -> gcd x y == 1)]
<*> [pythagoreanTriplesBelow 100]
)</
{{Out}}
<pre>17
Line 2,556:
Recursive primitive generation:
<
triangles max_peri
| max_peri < 12 = []
Line 2,579:
mapM_
((putStrLn . (\n -> show n <> " " <> show (triangleCount n))) . (10 ^))
[1 .. 7]</
{{out}}
<pre>10 (0,0)
Line 2,592:
This uses the elegant formula (#IV) from [[wp:Formulas_for_generating_Pythagorean_triples|Formulas for generating Pythagorean triples]]
<syntaxhighlight lang="icon">
link numbers
link printf
Line 2,630:
every (s := "") ||:= !sort(x) do s ||:= ","
return s[1:-1]
end</
{{libheader|Icon Programming Library}}
Line 2,664:
Brute force approach:
<
r=. i. 0 3
for_a. 1 + i. <.(y-1)%3 do.
Line 2,677:
)
prim=: 1 = 2 +./@{. |:</
Example use:
Line 2,683:
First column indicates whether the triple is primitive, and the remaining three columns are a, b and c.
<
1 3 4 5
1 5 12 13
Line 2,708:
325 70
(# , [: {. +/) pytr 10000
4858 703</
pytr 10000 takes 4 seconds on this laptop, and time to complete grows with square of perimeter, so pytr 1e6 should take something like 11 hours using this algorithm on this machine.
Line 2,714:
A slightly smarter approach:
<
'm n'=. |:(#~ 1 = 2 | +/"1)(#~ >/"1) ,/ ,"0/~ }. i. <. %: y
prim=. (#~ 1 = 2 +./@{. |:) (#~ y >: +/"1)m (-&*: ,. +:@* ,. +&*:) n
/:~ ; <@(,.~ # {. 1:)@(*/~ 1 + y i.@<.@% +/)"1 prim
)</
usage for trips is the same as for pytr. Thus:
<
0 0
(# , 1 {. +/) trips 100
Line 2,735:
808950 70229
(# , 1 {. +/) trips 10000000
9706567 702309</
The last line took about 16 seconds.
Line 2,741:
That said, we do not actually have to generate all the triples, we just need to count them. Thus:
<
'm n'=. |:(#~ 1 = 2 | +/"1)(#~ >/"1) ,/ ,"0/~ }. i. <. %: y
<.y%+/"1 (#~ 1 = 2 +./@{. |:) (#~ y >: +/"1)m (-&*: ,. +:@* ,. +&*:) n
)</
The result is a list of positive integers, one number for each primitive triple which fits within the limit, giving the number of triples which are multiples of that primitive triple whose perimeter is no greater than the limiting perimeter.
<syntaxhighlight lang="text"> (#,+/)trc 1e8
7023027 113236940</
But note that J's memory footprint reached 6.7GB during the computation, so to compute larger values the computation would have to be broken up into reasonable sized blocks.
===Traversal of the Tree of Primitive Pythagorean Triples===
On my laptop this code takes 1.35 seconds for a perimeter of up to 1 million, though it takes 2 minutes for 10 million, so performance is between the previous code "brute force" and what is called "slightly smarter approach" It could probably be sped up slightly by not sorting the triples (there is no need with this problem.)
<syntaxhighlight lang="j">
mp =: +/ . * "2 1
Line 2,785:
echo count 10 ^ >: i.6
exit ''
</syntaxhighlight>
{{Out}}
<pre>
Line 2,800:
===Brute force===
[[Category:Arbitrary precision]]Theoretically, this can go "forever", but it takes a while, so only the minimum is shown. Luckily, <code>BigInteger</code> has a GCD method built in.
<
import java.math.BigInteger;
import static java.math.BigInteger.ONE;
Line 2,851:
+ tripCount + " triples, of which " + primCount + " are primitive.");
}
}</
Output:
<pre>3, 4, 5 primitive
Line 2,877:
{{works with|Java|1.5+}}
This can also go "forever" theoretically. Letting it go to another order of magnitude overflowed the stack on the computer this was tested on. This version also does not show the triples as it goes, it only counts them.
<
public class Triples{
Line 2,914:
}
}
}</
Output:
<pre>100: 17 triples, 7 primitive.
Line 2,926:
===ES6===
Exhaustive search of a full cartesian product. Not scalable.
<
"use strict";
Line 2,994:
// MAIN ---
return main();
})();</
{{Out}}
<
{"maxPerimeter":100, "triples":17, "primitives":7},
{"maxPerimeter":1000, "triples":325, "primitives":70}]</
=={{header|jq}}==
Line 3,006:
The implementation illustrates how an inner function with arity 0 can
attain a high level of efficiency with both jq 1.4 and later. A simpler implementation is possible with versions of jq greater than 1.4.
<
def _gcd:
if .[1] == 0 then .[0]
Line 3,043:
range(1; 9) | . as $i | 10|pow($i) as $i | "\($i): \(count($i) )"
</syntaxhighlight>
{{Out}}
<
10: [0,0]
100: [17,7]
Line 3,054:
10000000: [9706567,702309]
100000000: [113236940,7023027]
</syntaxhighlight>
=={{header|Julia}}==
This solution uses the the Euclidian concept of m and n as generators of Pythagorean triplets. When m and n are coprime and have opposite parity, the generated triplets are primitive. It works reasonably well up to a limit of 10^10.
<syntaxhighlight lang="julia">
function primitiven{T<:Integer}(m::T)
1 < m || return T[]
Line 3,096:
println(@sprintf " 10^%02d %11d %9d" om fcnt pcnt)
end
</syntaxhighlight>
{{out}}
Line 3,117:
{{trans|Go}}
Due to deep recursion, I needed to increase the stack size to 4MB to get up to a maximum perimeter of 10 billion. Expect a run time of around 30 seconds on a typical laptop.
<
var total = 0L
Line 3,143:
maxPeri *= 10
}
}</
{{out}}
Line 3,159:
=={{header|Lasso}}==
<
define num_pythagorean_triples(max_perimeter::integer) => {
local(max_b) = (#max_perimeter / 3)*2
Line 3,177:
stdout(`Number of Pythagorean Triples in a Perimeter of 100: `)
stdoutnl(num_pythagorean_triples(100))
</syntaxhighlight>
Output:
<pre>Number of Pythagorean Triples in a Perimeter of 100: 17
Line 3,183:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
print time$()
Line 3,228:
print "End"
end
</syntaxhighlight>
<pre>
17:59:34
Line 3,248:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=== Brute force ===
<
Now prepare timings
<syntaxhighlight lang="mathematica">
pTiming[n_] := With[{comp = Timing@pythag@(10^n)},
{HoldForm[10^n], comp[[2, 1]], comp[[2, 2]], Round@comp[[1]]}];
{{"n", "Triples", "Primitives", "Timing(s)"}}~Join~(pTiming /@ Range@5) // Grid
</syntaxhighlight>
{{out}}
Line 3,272:
The following uses generating formulae and is adapted from [[:https://mathematica.stackexchange.com/a/15904/2249]]
<
Now prepare timings
<
{{"n", "Primitives", "Timing(s)"}}~Join~(ppTiming /@ Range@9) // Grid</
{{out}}
Line 3,296:
=={{header|MATLAB}} / {{header|Octave}}==
<
a = 1:N;
b = a(ones(N,1),:).^2;
Line 3,311:
printf('There are %i Pythagorean Triples and %i primitive triples with a perimeter smaller than %i.\n',...
sum(ix), length(p), N); </
Output:
Line 3,320:
From [[List comprehensions]]:
<
:- module comprehension.
:- interface.
Line 3,343:
solutions((pred(Triple::out) is nondet :- pythTrip(20,Triple)),Result),
write(Result,!IO).
</syntaxhighlight>
=={{header|Modula-3}}==
Note that this code only works on 64bit machines (where <tt>INTEGER</tt> is 64 bits). Modula-3 provides a <tt>LONGINT</tt> type, which is 64 bits on 32 bit systems, but there is a bug in the implementation apparently.
<
IMPORT IO, Fmt;
Line 3,377:
i := i * 10;
UNTIL i = 10000000;
END PyTriple64.</
Output:
Line 3,391:
===Brute force method===
{{trans|Java}}
<
// a function to check if three numbers are a valid triple
Line 3,435:
print "Up to a perimeter of " + perimeter + ", there are " + ts
println " triples, of which " + ps + " are primitive."</
{{out}}
<pre>3, 4, 5 primitive
Line 3,459:
Compile with option <code>-d:release</code>. Without release option (i.e. in debug mode), the programs ends prematurely by reaching the recursion depth limit.
{{trans|C}}
<
[ 1, 2, 2, 2, 1, 2, 2, 2, 3],
[-1, 2, 2, -2, 1, 2, -2, 2, 3]]
Line 3,483:
newTri([3, 4, 5])
echo "Up to ", maxPeri, ": ", total, " triples, ", prim, " primitives"
maxPeri *= 10</
Output:
<pre>Up to 10: 0 triples, 0 primitives
Line 3,495:
=={{header|OCaml}}==
<
let rec iter t =
let d = n - t*t in
Line 3,527:
Printf.printf "For perimeters up to %d there are %d total and %d primitive\n%!" i s p;;
List.iter show [ 100; 1000; 10000; 100000; 1000000; 10000000; 100000000 ]</
Output:
<pre>For perimeters up to 100 there are 17 total and 7 primitive
Line 3,538:
=={{header|Ol}}==
<
; triples generator based on Euclid's formula, creates lazy list
(define (euclid-formula max)
Line 3,567:
(print max ": " (calculate max)))
(map (lambda (n) (expt 10 n)) (iota 6 1)))
</syntaxhighlight>
{{out}}
Line 3,581:
=={{header|PARI/GP}}==
This version is reasonably efficient and can handle inputs like a million quickly.
<
my(prim,total,P);
lim\=1;
Line 3,595:
[prim,total]
};
do(100)</
=={{header|Pascal}}==
<
var
Line 3,628:
maxPeri := maxPeri * 10;
end;
end.</
Output (on Core2Duo 2GHz laptop):
<pre>time ./PythagoreanTriples
Line 3,643:
=={{header|Perl}}==
<
my ($n, $m) = @_;
while($n){
Line 3,669:
tripel 10**$_ for 1..8;
</syntaxhighlight>
{{out}}
<pre>Max. perimeter: 10, Total: 0, Primitive: 0
Line 3,683:
=={{header|Phix}}==
{{Trans|Pascal}}
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">prim</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">maxPeri</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span>
Line 3,705:
<span style="color: #000000;">maxPeri</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">;</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</
{{out}}
<pre>
Line 3,719:
=={{header|PHP}}==
<
function gcd($a, $b)
Line 3,755:
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';</
{{out}}<pre>Up to 100, there are 17 triples, of which 7 are primitive.</pre>
Line 3,761:
===Prolog-style===
{{trans|Prolog}}
<
garbage_collect(300_000_000),
Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000],
Line 3,796:
order2(A, B, A, B) :- A < B, !.
order2(A, B, B, A).</
{{out}}
Line 3,813:
Picat doesn't have global variables, so all parameters are placed in the call to <code>newTri/6</code>. This is slightly faster than the Prolog port.
<
foreach(MaxPeri in [10**I : I in 2..8])
[Total, Prim] = newTri(MaxPeri,0,0,3,4,5),
Line 3,832:
PrimRet = Prim,
TotalRet = Total
end.</
{{out}}
Line 3,847:
===With "global variables"===
Actually, Picat has some support for global variables, using the global available map (<code>get_global_map</code>).
<
foreach(MaxPeri in [10**I : I in 2..8])
Map = get_global_map(),
Line 3,866:
newTri2(+1*S0+2*S1+2*S2, +2*S0+1*S1+2*S2, +2*S0+2*S1+3*S2),
newTri2(-1*S0+2*S1+2*S2, -2*S0+1*S1+2*S2, -2*S0+2*S1+3*S2)
end.</
This version is - however - slower: 7.401s.
Line 3,872:
=={{header|PicoLisp}}==
{{trans|C}}
<
(let (Total 0 Prim 0 In (3 4 5))
(recur (In)
Line 3,886:
(recurse
(mapcar '((U) (sum * U In)) Row) ) ) ) ) )
(prinl "Up to " Max ": " Total " triples, " Prim " primitives.") ) )</
Output:
<pre>Up to 10: 0 triples, 0 primitives.
Line 3,899:
=={{header|PL/I}}==
Version 1
<
/*********************************************************************
* REXX pgm counts number of Pythagorean triples
Line 3,988:
End;
End;</
Version 2
<syntaxhighlight lang="pl/i">
pythagorean: procedure options (main, reorder); /* 23 January 2014 */
declare (a, b, c) fixed (3);
Line 4,022:
end GCD;
end pythagorean;</
Output:
<pre>
Line 4,033:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function triples($p) {
if($p -gt 4) {
Line 4,084:
"There are $(($triples).Count) Pythagorean triples with perimeter no larger than 100
and $(($coprime).Count) of them are coprime."
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 4,091:
=={{header|Prolog}}==
<
show :-
Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000],
Line 4,129:
order2(A, B, A, B) :- A < B, !.
order2(A, B, B, A).
</syntaxhighlight>
{{Out}}
Line 4,153:
<math>n \le 10,000</math><br /><br />
<
Procedure.i ConsoleWrite(t.s) ; compile using /CONSOLE option
Line 4,222:
ConsoleWrite("")
et=ElapsedMilliseconds()-st:ConsoleWrite("Elapsed time = "+str(et)+" milliseconds")
</syntaxhighlight>
Line 4,246:
=={{header|Python}}==
Two methods, the second of which is much faster
<
Line 4,302:
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
</syntaxhighlight>
;Output:
Line 4,362:
Up to a perimeter of 19500 there are 10388 triples, of which 1373 are primitive
Up to a perimeter of 20000 there are 10689 triples, of which 1408 are primitive</pre>
Barebone minimum for this task:<
setrecursionlimit(2000) # 2000 ought to be big enough for everybody
Line 4,375:
for peri in [10 ** e for e in range(1, 8)]:
print peri, triples(peri)</
100 (7, 17)
1000 (70, 325)
Line 4,381:
100000 (7026, 64741)
1000000 (70229, 808950)
10000000 (702309, 9706567)</
=={{header|Racket}}==
<
#| Euclid's enumeration formula and counting is fast enough for extra credit.
Line 4,428:
113236940, 7023027.
cpu time: 11976 real time: 12215 gc time: 2381
|#</
=={{header|Raku}}==
Line 4,434:
{{works with|Rakudo|2018.09}}
Here is a straight-forward, naive brute force implementation:
<syntaxhighlight lang="raku"
for [X] [^limit] xx 3 -> (\a, \b, \c) {
say [a, b, c] if a < b < c and a**2 + b**2 == c**2
}</
{{out}}
<pre style="height:25ex">3 4 5
Line 4,490:
65 72 97</pre>
Here is a slightly less naive brute force implementation, but still not practical for large perimeter limits.
<syntaxhighlight lang="raku"
my atomicint $i = 0;
my @triples[$limit/2];
Line 4,503:
say my $result = "There are {+@triples.grep:{$_ !eqv Any}} Pythagorean Triples with a perimeter <= $limit,"
~"\nof which {[+] @triples.grep: so *} are primitive.";</
{{out}}
<pre>There are 4858 Pythagorean Triples with a perimeter <= 10000,
of which 703 are primitive.</pre>
Here's a much faster version. Hint, "oyako" is Japanese for "parent/child". <tt>:-)</tt>
<syntaxhighlight lang="raku"
my $primitive = 0;
my $civilized = 0;
Line 4,527:
for 10,100,1000 ... * -> $limit {
say triples $limit;
}</
Output:
<pre>10 => (0 0)
Line 4,542:
Here is an alternate version that avoids naming any scalars that can be handled by vector processing instead. Using vectorized ops allows a bit more potential for parallelization in theory, but techniques like the use of complex numbers to add two numbers in parallel, and the use of <tt>gather</tt>/<tt>take</tt> generate so much overhead that this version runs 70-fold slower than the previous one.
<syntaxhighlight lang="raku"
[[+1, +2, +2], [+2, +1, +2], [+2, +2, +3]],
[[-1, +2, +2], [-2, +1, +2], [-2, +2, +3]];
Line 4,564:
for 10, 100, 1000, 10000 -> $limit {
say triples $limit;
}</
{{out}}
<pre>10 => (0 0)
Line 4,573:
=={{header|REXX}}==
===using GCD for determinacy===
<
/*──────────────────── perimeter of N, and also counts how many of them are primitives.*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,598:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gcd: procedure; parse arg x,y; do until y==0; parse value x//y y with y x; end; return x</
{{out|output|text= when using the default input of: <tt> 100 </tt>}}
<pre>
Line 4,614:
Non-primitive Pythagorean triples are generated after a primitive triple is found.
<
/*──────────────────── perimeter of N, and also counts how many of them are primitives.*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,642:
end /*a*/ /*stick a fork in it, we're all done. */
_= left('', 7) /*for padding the output with 7 blanks.*/
say 'max perimeter =' N _ "Pythagorean triples =" T _ 'primitives =' P</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}}<br><br>
Line 4,651:
=={{header|Ring}}==
<
size = 100
sum = 0
Line 4,675:
end
return gcd
</syntaxhighlight>
Output:
<pre>
Line 4,701:
=={{header|Ruby}}==
{{trans|Java}}
<
def initialize(limit)
@limit = limit
Line 4,729:
p [perim, c.total, c.primitives]
perim *= 10
end</
output
Line 4,742:
=={{header|Rust}}==
<
fn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 {
Line 4,787:
new_th_1.join().unwrap();
new_th_2.join().unwrap();
}</
{{out}}
<pre> Primitive triples below 100 : 7
Line 4,816:
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/CAz60TW/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/soOLJ673Q82l78OCgIx4oQ Scastie (remote JVM)].
<
println(" Limit Primatives All")
Line 4,840:
println(f"a + b + c <= ${limit.toFloat}%3.1e $primCount%9d $tripCount%12d")
}
}</
=={{header|Scheme}}==
{{works with|Gauche Scheme}}
<
(define (py perim)
Line 4,855:
(begin (when (= 1 (gcd a b)) (inc! prim)))
1)
prim))</
<b>Testing:</b>
<pre>
Line 4,874:
The example below uses [http://seed7.sourceforge.net/libraries/bigint.htm bigInteger] numbers:
<
include "bigint.s7i";
Line 4,904:
max_peri *:= 10_;
end while;
end func;</
Output:
Line 4,920:
=={{header|Sidef}}==
{{trans|Raku}}
<
var primitive = 0
var civilized = 0
Line 4,940:
for n (1..Inf) {
say triples(10**n)
}</
{{out}}
Line 4,955:
=={{header|Swift}}==
{{trans|Pascal}}
<
var prim = 0
var maxPeri = 100
Line 4,977:
print("Up to \(maxPeri) : \(total) triples \( prim) primitives.")
maxPeri *= 10
}</
{{out}}
Line 4,993:
Using the efficient method based off the Wikipedia article:
<!--There's no technical reason to limit the code to just these values, but generation does get progressively slower with larger maximum perimiters. 10M is about as much as I have patience for; I'm generally impatient! -->
<
lappend q 3 4 5
set idx [set count [set prim 0]]
Line 5,017:
lassign [countPythagoreanTriples $i] count primitive
puts "perimeter limit $i => $count triples, $primitive primitive"
}</
Output:
<pre>
Line 5,030:
=={{header|VBA}}==
{{trans|Pascal}}<
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
Line 5,051:
maxPeri = maxPeri * 10
Loop
End Sub</
<pre>Up to 100 : 17 triples, 7 primitives.
Up to 1000 : 325 triples, 70 primitives.
Line 5,062:
=={{header|VBScript}}==
{{trans|Perl}}
<syntaxhighlight lang="vb">
For i=1 To 8
WScript.StdOut.WriteLine triples(10^i)
Line 5,099:
Loop
End Function
</syntaxhighlight>
=={{header|Visual Basic}}==
Line 5,108:
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
<
Dim total As Long, prim As Long, maxPeri As Long
Line 5,135:
maxPeri = maxPeri * 10
Loop
End Sub</
{{out}}
<pre>Up to 100 : 17 triples, 7 primitives.
Line 5,148:
{{trans|Go}}
Limited to a maximum perimeter of 10 billion in order to finish in a reasonable time.
<
var total = 0
var prim = 0
Line 5,173:
System.print("Up to %(maxPeri): %(total) triples, %(prim) primitives, %(secs) seconds")
maxPeri = 10 * maxPeri
}</
{{out}}
Line 5,191:
=={{header|XPL0}}==
Simple minded algorithm:
<
int N, D, R; \numerator and denominator
[if D > N then
Line 5,225:
Max:= Max*10;
until Max > 10_000;
]</
{{out}}
Line 5,236:
{{trans|Go}}
<
proc NewTri(S0, S1, S2);
Line 5,261:
MaxPeri:= MaxPeri*10;
];
]</
{{out}}
Line 5,277:
=={{header|zkl}}==
{{trans|D}}
<
p:=a + b + c;
if(p>lim) return(0,0);
Line 5,285:
tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c)
);
}</
<
{{out}}
<pre>10: L(0,0)
Line 5,319:
Set in line nr: 11 IF L<=1000 THEN GO TO 2
<
2 FOR U=2 TO INT (SQR (L/2)): LET Y=U-INT (U/2)*2: LET N=N+4: LET M=U*U*2: IF Y=0 THEN LET M=M-U-U
3 FOR V=1+Y TO U-1 STEP 2: LET M=M+N: LET X=U: LET Y=V
Line 5,329:
9 NEXT U
10 PRINT L;TAB 8;T;TAB 16;P
11 LET N=4: LET T=0: LET P=0: LET L=L*10: IF L<=100000 THEN GO TO 2</
{{out}}
<pre>limit trip. prim.
|