Pythagorean triples: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(→‎{{header|Wren}}: Typo in program comment.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(34 intermediate revisions by 25 users not shown)
Line 24:
*   [[Pythagorean quadruples]]
<br><br>
 
=={{header|11l}}==
{{trans|D}}
 
<syntaxhighlight lang="11l">Int64 nTriples, nPrimitives, limit
 
F countTriples(Int64 =x, =y, =z)
L
V p = x + y + z
I p > :limit
R
 
:nPrimitives++
:nTriples += :limit I/ p
 
V t0 = x - 2 * y + 2 * z
V t1 = 2 * x - y + 2 * z
V t2 = t1 - y + z
countTriples(t0, t1, t2)
 
t0 += 4 * y
t1 += 2 * y
t2 += 4 * y
countTriples(t0, t1, t2)
 
z = t2 - 4 * x
y = t1 - 4 * x
x = t0 - 2 * x
 
L(p) 1..8
limit = Int64(10) ^ p
nTriples = nPrimitives = 0
countTriples(3, 4, 5)
print(‘Up to #11: #11 triples, #9 primitives.’.format(limit, nTriples, nPrimitives))</syntaxhighlight>
 
{{out}}
<pre>
Up to 10: 0 triples, 0 primitives.
Up to 100: 17 triples, 7 primitives.
Up to 1000: 325 triples, 70 primitives.
Up to 10000: 4858 triples, 703 primitives.
Up to 100000: 64741 triples, 7026 primitives.
Up to 1000000: 808950 triples, 70229 primitives.
Up to 10000000: 9706567 triples, 702309 primitives.
Up to 100000000: 113236940 triples, 7023027 primitives.
</pre>
 
=={{header|360 Assembly}}==
{{trans|Perl}}
<langsyntaxhighlight lang="360asm">* Pythagorean triples - 12/06/2018
PYTHTRI CSECT
USING PYTHTRI,R13 base register
Line 153 ⟶ 199:
ISQRTSA DS 8A context store
YREGS
END PYTHTRI</langsyntaxhighlight>
{{out}}
<pre>
Line 162 ⟶ 208:
Max Perimeter: 100000, Total: 64741, Primitive: 7026
Max Perimeter: 1000000, Total: 808950, Primitive: 70229
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
DEFINE ENTRY_SIZE="3"
TYPE TRIPLE=[BYTE a,b,c]
TYPE TRIPLES=[
PTR buf ;BYTE ARRAY
BYTE count]
 
PTR FUNC GetItemAddr(TRIPLES POINTER arr BYTE index)
PTR addr
 
addr=arr.buf+index*ENTRY_SIZE
RETURN (addr)
 
PROC PrintTriples(TRIPLES POINTER arr)
INT i
TRIPLE POINTER t
 
FOR i=0 TO arr.count-1
DO
t=GetItemAddr(arr,i)
PrintF("(%B %B %B) ",t.a,t.b,t.c)
OD
RETURN
 
PROC Init(TRIPLES POINTER arr BYTE ARRAY b)
arr.buf=b
arr.count=0
RETURN
 
PROC AddItem(TRIPLES POINTER arr TRIPLE POINTER t)
TRIPLE POINTER p
 
p=GetItemAddr(arr,arr.count)
p.a=t.a
p.b=t.b
p.c=t.c
arr.count==+1
RETURN
 
PROC FindTriples(TRIPLES POINTER res BYTE limit)
BYTE ARRAY data(100)
BYTE half,i,j,k
TRIPLE t
Init(res,data)
half=limit/2
FOR i=1 TO half
DO
FOR j=i TO half
DO
FOR k=j TO limit
DO
IF i+j+k<limit AND i*i+j*j=k*k THEN
t.a=i t.b=j t.c=k
AddItem(res,t)
FI
OD
OD
OD
RETURN
 
BYTE FUNC Gcd(BYTE a,b)
BYTE tmp
 
IF a<b THEN
tmp=a a=b b=tmp
FI
 
WHILE b#0
DO
tmp=a MOD b
a=b b=tmp
OD
RETURN (a)
 
BYTE FUNC IsPrimitive(TRIPLE POINTER t)
IF Gcd(t.a,t.b)>1 THEN RETURN (0) FI
IF Gcd(t.b,t.c)>1 THEN RETURN (0) FI
IF Gcd(t.a,t.c)>1 THEN RETURN (0) FI
RETURN (1)
 
PROC FindPrimitives(TRIPLES POINTER arr,res)
BYTE ARRAY data(100)
INT i
TRIPLE POINTER t
 
Init(res,data)
FOR i=0 TO arr.count-1
DO
t=GetItemAddr(arr,i)
IF IsPrimitive(t) THEN
AddItem(res,t)
FI
OD
RETURN
 
PROC Main()
DEFINE LIMIT="100"
TRIPLES res,res2
 
FindTriples(res,LIMIT)
PrintF("There are %B pythagorean triples with a perimeter less than %B:%E%E",res.count,LIMIT)
PrintTriples(res)
 
FindPrimitives(res,res2)
PrintF("%E%E%E%B of them are primitive:%E%E",res2.count)
PrintTriples(res2)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pythagorean_triples.png Screenshot from Atari 8-bit computer]
<pre>
There are 17 pythagorean triples with a perimeter less than 100:
 
(3 4 5) (5 12 13) (6 8 10) (7 24 25) (8 15 17) (9 12 15) (9 40 41) (10 24 26) (12 16 20)
(12 35 37) (15 20 25) (15 36 39) (16 30 34) (18 24 30) (20 21 29) (21 28 35) (24 32 40)
 
7 of them are primitive:
 
(3 4 5) (5 12 13) (7 24 25) (8 15 17) (9 40 41) (12 35 37) (20 21 29)
</pre>
 
Line 168 ⟶ 336:
Translation of efficient method from C, see [[wp:Pythagorean_triple#Parent.2Fchild_relationships|the WP article]]. Compiles on gnat/gcc.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Pythagorean_Triples is
Line 200 ⟶ 368:
Large_Natural'Image(P_Cnt) & " Primitives");
end loop;
end Pythagorean_Triples;</langsyntaxhighlight>
 
Output:
Line 214 ⟶ 382:
Up to 10 ** 9 : 1294080089 Triples, 70230484 Primitives</pre>
 
=={{header|ANSIALGOL Standard BASIC68}}==
Uses a table of square roots so OK for perimeters up to 1000 (or possibly 10 000).
<syntaxhighlight lang="algol68">
BEGIN # find some Pythagorean triples ( a, b, c ) #
# where a < b < c and a^2 + b^2 = c^2 #
 
INT max perimeter = 100; # maximum a + b + c we will consider #
Translation of BBC BASIC Program
INT max square = max perimeter * max perimeter;
# form a table of square roots of numbers to max perimeter ^ 2 #
[ 1 : max square ]INT sr;
FOR i TO UPB sr DO sr[ i ] := 0 OD;
FOR i TO max perimeter DO sr[ i * i ] := i OD;
 
PROC gcd = ( INT x, y )INT: # iterative gcd #
<lang ANSI Standard BASIC>100 DECLARE EXTERNAL SUB tri
BEGIN
110 !
INT a := ABS x, b := ABS y;
120 PUBLIC NUMERIC U0(3,3), U1(3,3), U2(3,3), all, prim
WHILE b /= 0 DO
130 DIM seed(3)
INT next a = b;
140 MAT READ U0, U1, U2
b := a MOD b;
150 DATA 1, -2, 2, 2, -1, 2, 2, -2, 3
160 DATA 1, 2, 2, 2, 1, 2, 2, 2, 3 a := next a
170 DATA -1, 2, 2, -2, 1, 2, -2, 2, 3 OD;
a
180 !
END # gcd # ;
190 MAT READ seed
 
200 DATA 3, 4, 5
# count the Pythagorean triples #
210 FOR power = 1 TO 7
220 INT LETt allcount := 0, p count := 0;
230 FOR LETa primTO max =perimeter 0DO
240 CALL tri(seed, 10^power ,INT alla2 ,= prim)a * a;
FOR b FROM a + 1 TO max perimeter - a
250 PRINT "Up to 10^";power,
WHILE INT c = sr[ a2 + ( b * b ) ];
260 PRINT USING "######### triples ######### primitives":all,prim
a + b + c <= max perimeter
270 NEXT power
DO IF c > b THEN # have a triple #
280 END
t count +:= 1;
290 !
IF gcd( a, b ) = 1 THEN # have a primitive triple #
300 EXTERNAL SUB tri(i(), mp, all, prim)
p count +:= 1
310 DECLARE EXTERNAL FUNCTION SUM
FI
320 DECLARE NUMERIC t(3)
FI
330 !
340 IF SUM(i) > mp THEN EXIT SUBOD
OD;
350 LET prim = prim + 1
print( ( "Pythagorean triples with perimeters up to ", whole( max perimeter, 0 ), ":", newline ) );
360 LET all = all + INT(mp / SUM(i))
print( ( " Primitive: ", whole( p count, 0 ), newline ) );
370 !
print( ( " Total: ", whole( t count, 0 ), newline ) )
380 MAT t = U0 * i
 
390 CALL tri(t, mp , all , prim)
END
400 MAT t = U1 * i
</syntaxhighlight>
410 CALL tri(t, mp , all , prim)
{{out}}
420 MAT t = U2 * i
<pre>
430 CALL tri(t, mp , all , prim)
Pythagorean triples with perimeters up to 100:
440 END SUB
Primitive: 7
450 !
Total: 17
460 EXTERNAL FUNCTION SUM(a())
</pre>
470 LET temp = 0
 
480 FOR i=LBOUND(a) TO UBOUND(a)
=={{header|Arturo}}==
490 LET temp = temp + a(i)
 
500 NEXT i
<syntaxhighlight lang="rebol">triples: new []
510 LET SUM = temp
loop 1..50 'x [
520 END FUNCTION</lang>
loop 1..50 'y [
loop (max @[x y])..100 'z [
if 100 > sum @[x y z] [
if (z^2) = add x^2 y^2 ->
'triples ++ @[sort @[x y z]]
]
]
]
]
unique 'triples
 
print ["Found" size triples "pythagorean triples with a perimeter no larger than 100:"]
print triples
 
primitive: select triples => [1 = gcd]
 
print ""
print [size primitive "of them are primitive:"]
print primitive</syntaxhighlight>
 
{{out}}
 
<pre>Found 17 pythagorean triples with a perimeter no larger than 100:
[3 4 5] [5 12 13] [6 8 10] [7 24 25] [8 15 17] [9 12 15] [9 40 41] [10 24 26] [12 16 20] [12 35 37] [15 20 25] [15 36 39] [16 30 34] [18 24 30] [20 21 29] [21 28 35] [24 32 40]
 
7 of them are primitive:
[3 4 5] [5 12 13] [7 24 25] [8 15 17] [9 40 41] [12 35 37] [20 21 29]</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
⍝ Determine whether given list of integers has GCD = 1
primitive←∧/1=2∨/⊢
⍝ Filter list given as right operand by applying predicate given as left operand
filter←{⍵⌿⍨⍺⍺ ⍵}
 
⍝ Function pytriples finds all triples given a maximum perimeter
∇res←pytriples maxperimeter;sos;sqrt;cartprod;ascending;ab_max;c_max;a_b_pairs;sos_is_sq;add_c;perimeter_rule
⍝ Input parameter maxperimeter is the maximum perimeter
⍝ Sum of squares of given list of nrs
sos←+/(×⍨⊢)
⍝ Square root
sqrt←(÷2)*⍨⊢
⍝ (cartesian product) all possible pairs of integers
⍝ from 1 to ⍵
cartprod←{,{⍺∘.,⍵}⍨⍳⍵}
⍝ Predicate: are values in given list ascending
⍝ Given e.g. pair a, b, c: is a ≤ b ≤ c?
ascending←∧/2≤/⊢
ab_max←⌊maxperimeter÷2
c_max←⌈maxperimeter×sqrt 2
⍝ Selects from all a,b combinations (a<abmax, b<abmax)
⍝ only those pairs where a ≤ b.
a_b_pairs←ascending filter¨cartprod(ab_max)
⍝ Predicate: is the sum of squares of a and b
⍝ itself a square? (does it occur in the squares list)
sos_is_sq←{{⍵≠1+c_max}(×⍨⍳c_max)⍳sos¨⍵}
⍝ Given a pair a,b add corresponding c to form a triple
add_c←{⍵,sqrt sos ⍵}
⍝ Predicate: sum of items less than or equal to max
perimeter_rule←{maxperimeter≥+/⍵}
res←perimeter_rule¨filter add_c¨sos_is_sq filter a_b_pairs
∇</syntaxhighlight>
{{out}}
<pre>
⍝ Get the number of triples
≢pytriples 100
17
⍝ Get the number of primitive triples
≢primitive¨filter pytriples 100
7
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">#NoEnv
SetBatchLines, -1
#SingleInstance, Force
Line 292 ⟶ 540:
 
Loop, 8
Msgbox % 10**A_Index ": " count_triples(10**A_Index)</langsyntaxhighlight>
 
{{out}}
Line 305 ⟶ 553:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PYTHAGOREAN_TRIPLES.AWK
# converted from Go
Line 329 ⟶ 577:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 344 ⟶ 592:
</pre>
 
=={{header|BBC BASIC}}==
==={{header|ANSI BASIC}}===
{{trans|BBC BASIC}}
{{works with|Decimal BASIC}}
<syntaxhighlight lang="basic">100 DECLARE EXTERNAL SUB tri
110 !
120 PUBLIC NUMERIC U0(3,3), U1(3,3), U2(3,3), all, prim
130 DIM seed(3)
140 MAT READ U0, U1, U2
150 DATA 1, -2, 2, 2, -1, 2, 2, -2, 3
160 DATA 1, 2, 2, 2, 1, 2, 2, 2, 3
170 DATA -1, 2, 2, -2, 1, 2, -2, 2, 3
180 !
190 MAT READ seed
200 DATA 3, 4, 5
210 FOR power = 1 TO 7
220 LET all = 0
230 LET prim = 0
240 CALL tri(seed, 10^power , all , prim)
250 PRINT "Up to 10^";power,
260 PRINT USING "######### triples ######### primitives":all,prim
270 NEXT power
280 END
290 !
300 EXTERNAL SUB tri(i(), mp, all, prim)
310 DECLARE EXTERNAL FUNCTION SUM
320 DECLARE NUMERIC t(3)
330 !
340 IF SUM(i) > mp THEN EXIT SUB
350 LET prim = prim + 1
360 LET all = all + INT(mp / SUM(i))
370 !
380 MAT t = U0 * i
390 CALL tri(t, mp , all , prim)
400 MAT t = U1 * i
410 CALL tri(t, mp , all , prim)
420 MAT t = U2 * i
430 CALL tri(t, mp , all , prim)
440 END SUB
450 !
460 EXTERNAL FUNCTION SUM(a())
470 LET temp = 0
480 FOR i=LBOUND(a) TO UBOUND(a)
490 LET temp = temp + a(i)
500 NEXT i
510 LET SUM = temp
520 END FUNCTION</syntaxhighlight>
{{out}}
<pre>
Up to 10^ 1 0 triples 0 primitives
Up to 10^ 2 17 triples 7 primitives
Up to 10^ 3 325 triples 70 primitives
Up to 10^ 4 4858 triples 703 primitives
Up to 10^ 5 64741 triples 7026 primitives
Up to 10^ 6 808950 triples 70229 primitives
Up to 10^ 7 9706567 triples 702309 primitives
</pre>
 
==={{header|BBC BASIC}}===
The built-in array arithmetic is very well suited to this task!
<langsyntaxhighlight lang="bbcbasic"> DIM U0%(2,2), U1%(2,2), U2%(2,2), seed%(2)
U0%() = 1, -2, 2, 2, -1, 2, 2, -2, 3
U1%() = 1, 2, 2, 2, 1, 2, 2, 2, 3
Line 372 ⟶ 678:
t%() = U2%() . i%()
PROCtri(t%(), mp%, all%, prim%)
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 387 ⟶ 693:
=={{header|Bracmat}}==
{{trans|C}}
<langsyntaxhighlight lang="bracmat">(pythagoreanTriples=
total prim max-peri U
. (.(1,-2,2) (2,-1,2) (2,-2,3))
Line 440 ⟶ 746:
pythagoreanTriples$;
</syntaxhighlight>
</lang>
 
Output (under Linux):
Line 455 ⟶ 761:
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.
 
<langsyntaxhighlight lang="bracmat">(pythagoreanTriples=
total prim max-peri U stack
. (.(1,-2,2) (2,-1,2) (2,-2,3))
Line 508 ⟶ 814:
);
 
pythagoreanTriples$;</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
Line 558 ⟶ 864:
 
return 0;
}</langsyntaxhighlight>output:<syntaxhighlight lang="text">Up to 100, there are 17 triples, of which 7 are primitive</langsyntaxhighlight>
Efficient method, generating primitive triples only as described in [[wp:Pythagorean_triple#Parent.2Fchild_relationships|the same WP article]]:<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 606 ⟶ 912:
}
return 0;
}</langsyntaxhighlight>Output<syntaxhighlight lang="text">Up to 10: 0 triples, 0 primitives.
Up to 100: 17 triples, 7 primitives.
Up to 1000: 325 triples, 70 primitives.
Line 613 ⟶ 919:
Up to 1000000: 808950 triples, 70229 primitives.
Up to 10000000: 9706567 triples, 702309 primitives.
Up to 100000000: 113236940 triples, 7023027 primitives.</langsyntaxhighlight>
 
Same as above, but with loop unwound and third recursion eliminated:
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 666 ⟶ 972:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
 
<syntaxhighlight lang="cpp">#include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>
 
using namespace std;
 
auto CountTriplets(unsigned long long maxPerimeter)
{
unsigned long long totalCount = 0;
unsigned long long primitveCount = 0;
auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
// The formulas below will generate primitive triples if:
// 0 < n < m
// m and n are relatively prime (gcd == 1)
// m + n is odd
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto perimeter = a + b + c;
if(perimeter <= maxPerimeter)
{
primitveCount++;
totalCount+= maxPerimeter / perimeter;
}
}
}
return tuple(totalCount, primitveCount);
}
 
 
int main()
{
vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
1000'000, 10'000'000, 100'000'000, 1000'000'000,
10'000'000'000}; // This last one takes almost a minute
for(auto maxPerimeter : inputs)
{
auto [total, primitive] = CountTriplets(maxPerimeter);
cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
}
}
</syntaxhighlight>
{{out}}
<pre>
Max Perimeter: 100, Total: 17, Primitive: 7
Max Perimeter: 1000, Total: 325, Primitive: 70
Max Perimeter: 10000, Total: 4858, Primitive: 703
Max Perimeter: 100000, Total: 64741, Primitive: 7026
Max Perimeter: 1000000, Total: 808950, Primitive: 70229
Max Perimeter: 10000000, Total: 9706567, Primitive: 702309
Max Perimeter: 100000000, Total: 113236940, Primitive: 7023027
Max Perimeter: 1000000000, Total: 1294080089, Primitive: 70230484
Max Perimeter: 10000000000, Total: 14557915466, Primitive: 702304875
</pre>
 
=={{header|C sharp|C#}}==
Line 672 ⟶ 1,048:
Based on Ada example, which is a translation of efficient method from C, see [[wp:Pythagorean_triple#Parent.2Fchild_relationships|the WP article]].
 
<langsyntaxhighlight Clang="c sharp">using System;
 
namespace RosettaCode.CSharp
Line 711 ⟶ 1,087:
}
}
}</langsyntaxhighlight>
 
Output:
Line 728 ⟶ 1,104:
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.
<langsyntaxhighlight lang="clojure">(defn gcd [a b] (if (zero? b) a (recur b (mod a b))))
(defn pyth [peri]
Line 744 ⟶ 1,120:
(reduce (fn [[total prims] t] [(inc total), (if (first t) (inc prims) prims)])
[0 0]
ts))</langsyntaxhighlight>
To handle really large perimeters, we can dispense with actually generating the triples and just calculate the counts:
<langsyntaxhighlight lang="clojure">(defn pyth-count [peri]
(reduce (fn [[total prims] k] [(+ total k), (inc prims)]) [0 0]
(for [m (range 2 (Math/sqrt (/ peri 2)))
Line 753 ⟶ 1,129:
:while (<= p peri)
:when (= 1 (gcd m n))]
(quot peri p))))</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="coffeescript">
gcd = (x, y) ->
return x if y == 0
Line 792 ⟶ 1,168:
max_perim = Math.pow 10, 9 # takes under a minute
count_triples(max_perim)
</syntaxhighlight>
</lang>
output
<pre>
Line 801 ⟶ 1,177:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun mmul (a b)
(loop for x in a collect
(loop for y in x
Line 817 ⟶ 1,193:
(format t "~a: ~a prim, ~a all~%" lim prim cnt)))
 
(loop for p from 2 do (count-tri (expt 10 p)))</langsyntaxhighlight>output<syntaxhighlight lang="text">100: 7 prim, 17 all
1000: 70 prim, 325 all
10000: 703 prim, 4858 all
Line 823 ⟶ 1,199:
1000000: 70229 prim, 808950 all
10000000: 702309 prim, 9706567 all
...</langsyntaxhighlight>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">class PythagoranTriplesCounter
def initialize(limit = 0)
@limit = limit
Line 856 ⟶ 1,232:
p [perim, c.total, c.primitives]
perim *= 10
end</langsyntaxhighlight>
 
output
Line 871 ⟶ 1,247:
===Lazy Functional Version===
With hints from the Haskell solution.
<langsyntaxhighlight lang="d">void main() @safe {
import std.stdio, std.range, std.algorithm, std.typecons, std.numeric;
 
Line 885 ⟶ 1,261:
writeln("Up to 100 there are ", xs.count, " triples, ",
xs.filter!q{ a[0] }.count, " are primitive.");
}</langsyntaxhighlight>
{{out}}
<pre>Up to 100 there are 17 triples, 7 are primitive.</pre>
 
===Shorter Version===
<langsyntaxhighlight lang="d">ulong[2] tri(ulong lim, ulong a=3, ulong b=4, ulong c=5)
pure nothrow @safe @nogc {
immutable l = a + b + c;
Line 906 ⟶ 1,282:
foreach (immutable p; 1 .. 9)
writeln(10 ^^ p, ' ', tri(10 ^^ p));
}</langsyntaxhighlight>
{{out}}
<pre>10 [0, 0]
Line 920 ⟶ 1,296:
===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).
<langsyntaxhighlight lang="d">import std.stdio, core.simd;
 
ulong2 tri(in ulong lim, in ulong a=3, in ulong b=4, in ulong c=5)
Line 937 ⟶ 1,313:
foreach (immutable p; 1 .. 9)
writeln(10 ^^ p, ' ', tri(10 ^^ p).array);
}</langsyntaxhighlight>
The output is the same. Run-time (32 bit system): about 0.67 seconds with ldc2.
 
===Faster Version===
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio;
 
alias Xuint = uint; // ulong if going over 1 billion.
Line 981 ⟶ 1,357:
limit, nTriples, nPrimitives);
}
}</langsyntaxhighlight>
{{out}}
<pre>Up to 10: 0 triples, 0 primitives.
Line 1,018 ⟶ 1,394:
Up to 10000000000: 14557915466 triples, 702304875 primitives.
Up to 100000000000: 161750315680 triples, 7023049293 primitives.</pre>
 
=={{header|Delphi}}==
See [[#Pascal|Pascal]].
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
global total prim maxperi .
proc newtri s0 s1 s2 . .
p = s0 + s1 + s2
if p <= maxperi
prim += 1
total += maxperi div p
newtri s0 - 2 * s1 + 2 * s2 2 * s0 - s1 + 2 * s2 2 * s0 - 2 * s1 + 3 * s2
newtri s0 + 2 * s1 + 2 * s2 2 * s0 + s1 + 2 * s2 2 * s0 + 2 * s1 + 3 * s2
newtri -s0 + 2 * s1 + 2 * s2 -2 * s0 + s1 + 2 * s2 -2 * s0 + 2 * s1 + 3 * s2
.
.
for maxperi in [ 100 10000000 ]
prim = 0
total = 0
newtri 3 4 5
print "Up to " & maxperi & ": " & total & " triples, " & prim & " primitives"
.
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
Line 1,027 ⟶ 1,428:
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).
<langsyntaxhighlight lang="edsac">
[Pythagorean triples for Rosetta code.
Counts (1) all Pythagorean triples (2) primitive Pythagorean triples,
with perimeter not greater than a given value.
 
Library subroutine M3, Prints header and is then overwritten.
Here, the last character sets the teleprinter to figures.]
Line 1,038 ⟶ 1,439:
@&*!MAX!PERIM!!!!!TOTAL!!!!!!PRIM@&#.
..PZ
 
[Library subroutine P7, prints long strictly positive integer;
10 characters, right justified, padded left with spaces.
Line 1,045 ⟶ 1,446:
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F
T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
 
[Subroutine for positive integer division.
Input: 4D = dividend, 6D = divisor.
Line 1,053 ⟶ 1,454:
GKA3FT35@A6DU8DTDA4DRDSDG13@T36@ADLDE4@T36@T6DA4DSDG23@
T4DA6DYFYFT6DT36@A8DSDE35@T36@ADRDTDA6DLDT6DE15@EFPF
 
[Subroutine to return GCD of two non-negative 35-bit integers.
Input: Integers at 4D, 6D.
Line 1,061 ⟶ 1,462:
GKA3FT39@S4DE37@T40@A4DTDA6DRDSDG15@T40@ADLDE6@T40@A6DSDG20@T6D
T40@A4DSDE29@T40@ADRDTDE16@S6DE39@TDA4DT6DSDT4DE5@A6DT4DEFPF
 
[************************ ROSETTA CODE TASK *************************
Subroutine to count Pythagorean triples with given maximum perimeter.
Line 1,074 ⟶ 1,475:
A 3 F [make link]
E 16 @ [jump over variables and constants]
 
[Double values are put here to ensure even address]
[Variables]
Line 1,083 ⟶ 1,484:
[10] P F P F [n]
[Constants]
T12#Z PF T12Z [clears sandwich digit between 12 and 13]
[12] P D P F [double-value 1]
T14#Z PF T14Z [clears sandwich digit between 14 and 15]
[14] P1F P F [double-value 2]
 
[Continue with code]
[16] T 69 @ [plant link for return]
Line 1,149 ⟶ 1,552:
T 6 D [return in 6D]
[69] E F
 
[2nd-level subroutine to count triangles arising from m, n.
Assumes m, n are coprime and of opposite parity,
Line 1,178 ⟶ 1,581:
T 6 D [return count = 0]
[91] E F
 
[Main routine. Load at an even address.]
T 500 K
G K
[The initial maximum perimeter is repeatedly multiplied by 10]
T#Z PF TZ [clears sandwich digit between 0 and 1]
[0] P50F PF [initial maximum perimeter <---------- EDIT HERE]
[2] P 3 F [number of values to calculate <---------- EDIT HERE]
Line 1,238 ⟶ 1,642:
E 15 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,251 ⟶ 1,655:
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,299 ⟶ 1,703:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,311 ⟶ 1,715:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def count_triples(limit), do: count_triples(limit,3,4,5)
Line 1,324 ⟶ 1,728:
 
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)</langsyntaxhighlight>
 
{{out}}
Line 1,340 ⟶ 1,744:
=={{header|Erlang}}==
 
<syntaxhighlight lang="erlang">%%
<lang Erlang>%%
%% Pythagorian triples in Erlang, J.W. Luiten
%%
Line 1,384 ⟶ 1,788:
L = lists:seq(1, Max),
Answer = lists:map(fun(X) -> count_triples(X) end, L),
lists:foreach(fun(Result) -> display_result(Result) end, Answer).</langsyntaxhighlight>
 
Output:
Line 1,402 ⟶ 1,806:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM PIT
 
BEGIN
Line 1,460 ⟶ 1,864:
 
PRINT PRINT("** End **")
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>16:08:39
Line 1,482 ⟶ 1,886:
=={{header|Euphoria}}==
{{trans|D}}
<langsyntaxhighlight lang="euphoria">function tri(atom lim, sequence in)
sequence r
atom p
Line 1,502 ⟶ 1,906:
? tri(max_peri, {3, 4, 5})
max_peri *= 10
end while</langsyntaxhighlight>
 
Output:
Line 1,517 ⟶ 1,921:
=={{header|F_Sharp|F#}}==
{{trans|OCaml}}
<langsyntaxhighlight lang="fsharp">let isqrt n =
let rec iter t =
let d = n - t*t
Line 1,548 ⟶ 1,952:
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 ]</langsyntaxhighlight>
{{out}}
<pre>For perimeters up to 100 there are 17 total and 7 primitive
Line 1,561 ⟶ 1,965:
Pretty slow (100 times slower than C)...
 
<langsyntaxhighlight lang="factor">USING: accessors arrays formatting kernel literals math
math.functions math.matrices math.ranges sequences ;
IN: rosettacode.pyth
Line 1,603 ⟶ 2,007:
"Up to %d: %d triples, %d primitives.\n" printf ;
: pyth ( -- )
8 [1,b] [ 10^ dup count-triplets pprint-triplet-count ] each ;</langsyntaxhighlight>
 
<pre>Up to 10: 0 triples, 0 primitives.
Line 1,618 ⟶ 2,022:
 
 
<syntaxhighlight lang="forth ">
<lang Forth >
 
 
Line 1,791 ⟶ 2,195:
ok
 
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{trans|C efficient method}}
<langsyntaxhighlight lang="fortran">module triples
implicit none
Line 1,841 ⟶ 2,245:
max_peri = max_peri * 10
end do
end program Pythagorean</langsyntaxhighlight>
Output:<pre>Up to 10 0 triples 0 primitives
Up to 100 17 triples 7 primitives
Line 1,858 ⟶ 2,262:
===Version 1===
Normal version
<langsyntaxhighlight lang="freebasic">' version 30-05-2016
' compile with: fbc -s console
 
Line 1,947 ⟶ 2,351:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>below triples primitive time
Line 1,968 ⟶ 2,372:
Attempt to make a faster version (about 20% faster)
 
<langsyntaxhighlight lang="freebasic">' version 30-05-2016
' compile with: fbc -s console
 
Line 2,049 ⟶ 2,453:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>below triples primitive time
Line 2,075 ⟶ 2,479:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,099 ⟶ 2,503:
maxPeri, total, prim)
}
}</langsyntaxhighlight>
Output:
<pre>
Line 2,117 ⟶ 2,521:
===Parent/Child Algorithm===
Solution:
<langsyntaxhighlight lang="groovy">class Triple {
BigInteger a, b, c
def getPerimeter() { this.with { a + b + c } }
Line 2,152 ⟶ 2,556:
}
}
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">printf (' LIMIT PRIMATIVE ALL\n')
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)
}</langsyntaxhighlight>
 
Output:
Line 2,176 ⟶ 2,580:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">pytr :: Int -> [(Bool, Int, Int, Int)]
pytr n =
filter
(\(_, a, b, c) -> a + b + c <= n)
[ (prim a b c, a, b, c)
| a <- xs ,
, b <- drop a xs ,
, c <- drop b xs ,
, a ^ 2 + b ^ 2 == c ^ 2 ]
]
where
xs = [1 .. n]
Line 2,192 ⟶ 2,597:
main =
putStrLn $
"Up to 100 there are " ++
<> show (length xs) ++
<> " triples, of which " ++
<> show (length $ filter (\(x, _, _, _) -> x) xs) ++ " are primitive."
<> " are primitive."
where
xs = pytr 100</langsyntaxhighlight>
 
{{Out}}
Line 2,203 ⟶ 2,609:
 
Or equivalently (desugaring the list comprehension down to nested concatMaps, and pruning back the search space a little):
<syntaxhighlight lang="haskell">------------------- PYTHAGOREAN TRIPLES ------------------
<lang haskell>pythagoreanTriplesBelow :: Int -> [[Int]]
 
pythagoreanTriplesBelow :: Int -> [[Int]]
pythagoreanTriplesBelow n =
concatMap
let m = quot n 2
in concatMap ( \x ->
(\x ->concatMap
(\y -> concatMap (go x y) [y + 1 .. m])
[x + 1 (\y.. ->m]
)
concatMap
[1 .. (\z ->m]
where
if x + y + z <= n && x ^ 2 + y ^ 2 == z ^ 2
m = quot n 2
then [[x, y, z]]
go x y z
else [])
| x + y + z <= n && x ^ 2 + [y +^ 2 == z 1^ ..2 m])=
[[x, +y, 1 .. mz]])
| [1otherwise ..= m[]
 
-- TEST ------------------------------------------------ TEST -------------------------
main :: IO ()
main =
mapM_
(print . length)
( [id, filter (\[x, y, _] -> gcd x y == 1)] <*> [pythagoreanTriplesBelow 100])</lang>
<*> [pythagoreanTriplesBelow 100]
)</syntaxhighlight>
{{Out}}
<pre>17
Line 2,230 ⟶ 2,640:
 
Recursive primitive generation:
<langsyntaxhighlight lang="haskell">triangles :: Int -> [[Int]]
triangles max_peri
| max_peri < 12 = []
Line 2,240 ⟶ 2,650:
map
(map (sum . zipWith (*) t))
[ [[1, -2, 2], [2, -1, 2], [2, -2, 3]],
, [[1, 2, 2], [2, 1, 2], [2, 2, 3]],
, [[-1, 2, 2], [-2, 1, 2], [-2, 2, 3]]
]
 
Line 2,252 ⟶ 2,662:
main =
mapM_
((putStrLn . (\n -> show n ++<> " " ++<> show (triangleCount n))) . (10 ^))
[1 .. 7]</langsyntaxhighlight>
{{out}}
<pre>10 (0,0)
Line 2,266 ⟶ 2,676:
This uses the elegant formula (#IV) from [[wp:Formulas_for_generating_Pythagorean_triples|Formulas for generating Pythagorean triples]]
 
<syntaxhighlight lang="icon">
<lang Icon>
link numbers
link printf
Line 2,304 ⟶ 2,714:
every (s := "") ||:= !sort(x) do s ||:= ","
return s[1:-1]
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 2,338 ⟶ 2,748:
Brute force approach:
 
<langsyntaxhighlight lang="j">pytr=: 3 :0
r=. i. 0 3
for_a. 1 + i. <.(y-1)%3 do.
Line 2,351 ⟶ 2,761:
)
 
prim=: 1 = 2 +./@{. |:</langsyntaxhighlight>
 
Example use:
Line 2,357 ⟶ 2,767:
First column indicates whether the triple is primitive, and the remaining three columns are a, b and c.
 
<langsyntaxhighlight lang="j"> pytr 100
1 3 4 5
1 5 12 13
Line 2,382 ⟶ 2,792:
325 70
(# , [: {. +/) pytr 10000
4858 703</langsyntaxhighlight>
 
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,388 ⟶ 2,798:
A slightly smarter approach:
 
<langsyntaxhighlight lang="j">trips=:3 :0
'm n'=. |:(#~ 1 = 2 | +/"1)(#~ >/"1) ,/ ,"0/~ }. i. <. %: y
prim=. (#~ 1 = 2 +./@{. |:) (#~ y >: +/"1)m (-&*: ,. +:@* ,. +&*:) n
/:~ ; <@(,.~ # {. 1:)@(*/~ 1 + y i.@<.@% +/)"1 prim
)</langsyntaxhighlight>
 
usage for trips is the same as for pytr. Thus:
 
<langsyntaxhighlight lang="j"> (# , 1 {. +/) trips 10
0 0
(# , 1 {. +/) trips 100
Line 2,409 ⟶ 2,819:
808950 70229
(# , 1 {. +/) trips 10000000
9706567 702309</langsyntaxhighlight>
 
The last line took about 16 seconds.
Line 2,415 ⟶ 2,825:
That said, we do not actually have to generate all the triples, we just need to count them. Thus:
 
<langsyntaxhighlight lang="j">trc=:3 :0
'm n'=. |:(#~ 1 = 2 | +/"1)(#~ >/"1) ,/ ,"0/~ }. i. <. %: y
<.y%+/"1 (#~ 1 = 2 +./@{. |:) (#~ y >: +/"1)m (-&*: ,. +:@* ,. +&*:) n
)</langsyntaxhighlight>
 
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</langsyntaxhighlight>
 
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
 
T =: 3 3 3$ 1 _2 2 2 _1 2 2 _2 3 1 2 2 2 1 2 2 2 3 _1 2 2 _2 1 2 _2 2 3
 
branch =: dyad define NB. Go down one branch of the tree, usage: <perimeter> branch <triple>
(x >: +/"1 next) # next =. T (/:~ @ mp) y
)
 
pythag =: monad define NB. pythagorean triples with max perimeter
t1 =. 0 3$ 0
if. y >: 12 do.
t0 =. 1 3$ 3 4 5
while. #t0 > 0 do.
t =. {. t0
t1 =. t1, t
t0 =. (}. t0), y branch t
end.
end.
/:~ t1
)
 
count =: monad define "0 NB. count triples with max perimeter
y, (#t), +/ <. y % +/"1 t =. pythag y
)
 
(9!:11) 7 NB. change output precision
 
echo 'Counts of primitive and total number of Pythagorean triples with perimeter ≤ 10^n.'
echo count 10 ^ >: i.6
exit ''
</syntaxhighlight>
{{Out}}
<pre>
Counts of primitive and total number of Pythagorean triples with perimeter ≤ 10^n.
10 0 0
100 7 17
1000 70 325
10000 703 4858
100000 7026 64741
1000000 70229 808950
</pre>
 
=={{header|Java}}==
===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.
<langsyntaxhighlight lang="java">
import java.math.BigInteger;
import static java.math.BigInteger.ONE;
Line 2,481 ⟶ 2,935:
+ tripCount + " triples, of which " + primCount + " are primitive.");
}
}</langsyntaxhighlight>
Output:
<pre>3, 4, 5 primitive
Line 2,507 ⟶ 2,961:
{{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.
<langsyntaxhighlight lang="java5">import java.math.BigInteger;
 
public class Triples{
Line 2,544 ⟶ 2,998:
}
}
}</langsyntaxhighlight>
Output:
<pre>100: 17 triples, 7 primitive.
Line 2,556 ⟶ 3,010:
===ES6===
Exhaustive search of a full cartesian product. Not scalable.
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// Arguments: predicate, maximum perimeter
// pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int
const pythTripleCount = (p, maxPerim) => {
maxPerim => {
const xs = enumFromTo(1, Math.floor(maxPerim / 2));
const
xs = enumFromTo(1)(
Math.floor(maxPerim / 2)
);
 
return concatMap(x => return xs.flatMap(
concatMap(yx => xs.slice(x).flatMap(
concatMap(z y => xs.slice(y).flatMap(
z => ((x + y + z <= maxPerim) &&
((x * x) + (y * y) === z * z) &&
p(x, y, z)) ? [
[x, y, z]
] : [], // (Empty lists disappear under concatenation)
xs.slice(y)), xs.slice(x )), xs
)
).length;
};
 
// GENERIC FUNCTIONS ---------------------- TEST -----------------------
const main = () => [10, 100, 1000]
.map(n => ({
maxPerimeter: n,
triples: pythTripleCount(() => true)(n),
primitives: pythTripleCount(
(x, y) => gcd(x)(y) === 1
)(n)
}));
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) =>
xs.length > 0 ? [].concat.apply([], xs.map(f)) : [];
 
// ---------------- GENERIC FUNCTIONS ----------------
// enumFromTo :: Enum a => a -> a -> [a]
const enumFromTo = (m, n) =>
(typeof m !== 'number' ? (
enumFromToChar
) : enumFromToInt)
.apply(null, [m, n]);
 
// enumFromToIntabs :: IntNum -> Int -> [Int]Num
const enumFromToIntabs = (m, n) =>
n// >=Absolute mvalue ?of Array.from({a given number
// without the length: Mathsign.floor(n - m) + 1
}, (_, i)x => m0 +> i)x :? [];(
-x
) : x;
 
// gcd :: Int -> Int -> Int
const gcd = (x, y) => {
const _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b));
return _gcd(Math.abs(x), Math.abs(y));
};
 
// enumFromTo :: Int -> Int -> [Int]
// MAIN ---------------------------------------------------
returnconst [10,enumFromTo 100,= 1000]m =>
.map(n => Array.from({
maxPerimeterlength: 1 + n, - m
}, (_, triples: pythTripleCount(xi) => true,m + ni),;
 
primitives: pythTripleCount((x, y, _) => gcd(x, y) === 1, n)
 
}));
// gcd :: Integral a => a -> a -> a
const gcd = x =>
y => {
const zero = x.constructor(0);
const go = (a, b) =>
zero === b ? (
a
) : go(b, a % b);
 
return go(abs(x), abs(y));
};
 
// MAIN ---
})();</lang>
return main();
})();</syntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[{"maxPerimeter":10, "triples":0, "primitives":0},
{"maxPerimeter":100, "triples":17, "primitives":7},
{"maxPerimeter":1000, "triples":325, "primitives":70}]</langsyntaxhighlight>
 
=={{header|jq}}==
Line 2,622 ⟶ 3,090:
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.
<langsyntaxhighlight lang="jq">def gcd(a; b):
def _gcd:
if .[1] == 0 then .[0]
Line 2,659 ⟶ 3,127:
 
range(1; 9) | . as $i | 10|pow($i) as $i | "\($i): \(count($i) )"
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -M -c -r -n -f Pythagorean_triples.jq
10: [0,0]
100: [17,7]
Line 2,670 ⟶ 3,138:
10000000: [9706567,702309]
100000000: [113236940,7023027]
</syntaxhighlight>
</lang>
 
=={{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">
<lang Julia>
function primitiven{T<:Integer}(m::T)
1 < m || return T[]
Line 2,712 ⟶ 3,180:
println(@sprintf " 10^%02d %11d %9d" om fcnt pcnt)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,733 ⟶ 3,201:
{{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.
<langsyntaxhighlight lang="scala">// version 1.1.2
 
var total = 0L
Line 2,759 ⟶ 3,227:
maxPeri *= 10
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,775 ⟶ 3,243:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">// Brute Force: Too slow for large numbers
define num_pythagorean_triples(max_perimeter::integer) => {
local(max_b) = (#max_perimeter / 3)*2
Line 2,793 ⟶ 3,261:
stdout(`Number of Pythagorean Triples in a Perimeter of 100: `)
stdoutnl(num_pythagorean_triples(100))
</syntaxhighlight>
</lang>
Output:
<pre>Number of Pythagorean Triples in a Perimeter of 100: 17
Line 2,799 ⟶ 3,267:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
print time$()
 
Line 2,844 ⟶ 3,312:
print "End"
end
</syntaxhighlight>
</lang>
<pre>
17:59:34
Line 2,862 ⟶ 3,330:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=== Brute force ===
Short code but not a very scalable approach...
<langsyntaxhighlight Mathematicalang="mathematica">pythag[n_] := Block[{soln = Solve[{a^2 + b^2 == c^2, a + b + c <= n, 0 < a < b < c}, {a, b, c}, Integers]},{Length[soln],Count[GCD[a,b]/.soln,1]}]</syntaxhighlight>
{Length[soln], Count[GCD[a, b] == GCD[b, c] == GCD[c, a] == 1 /. soln, True]}
]</lang>
 
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}}
<pre>pythag[10]
{0,0}
 
<pre>
pythag[100]
n Triples Primitives Time(s)
{17, 7}
10^1 0 0 3
10^2 17 7 5
10^3 325 70 7
10^4 4858 703 12
10^5 64741 7026 175
 
</pre>
pythag[1000]
 
{325, 70}</pre>
=== Faster Primitives ===
The following uses generating formulae and is adapted from [[:https://mathematica.stackexchange.com/a/15904/2249]]
 
<syntaxhighlight lang="mathematica">primitivePythag[p_] := Join @@ Table[If[CoprimeQ[m, n], {2 m n, m^2 - n^2, m^2 + n^2}, ## &[]],{m, 2, Floor @ Sqrt @ p},{n, 1 + m ~Mod~ 2, m, 2}] // Select[Total[#] <= p &] // Length</syntaxhighlight>
 
Now prepare timings
 
<syntaxhighlight lang="mathematica">ppTiming[n_] := With[{comp = Timing@primitivePythag@(10^n)},{HoldForm[10^n], comp[[2]], Round@comp[[1]]}];
{{"n", "Primitives", "Timing(s)"}}~Join~(ppTiming /@ Range@9) // Grid</syntaxhighlight>
{{out}}
 
<pre>
n Primitives Time(s)
10^1 0 0
10^2 7 0
10^3 70 0
10^4 703 0
10^5 7026 0
10^6 70229 1
10^7 702309 10
10^8 7023027 111
10^9 70230484 1111
</pre>
 
The primitive counts are where the computational grunt-work lies (multiples under the limit can be readily computed) and this meets task challenge up to 10^8. "Faster Primitive" generates all triples and further, doesn't take advantage of built-in compilation which would need to be exploited if further order-of-magnitude improvements were required.
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab">N= 100;
a = 1:N;
b = a(ones(N,1),:).^2;
Line 2,894 ⟶ 3,395:
 
printf('There are %i Pythagorean Triples and %i primitive triples with a perimeter smaller than %i.\n',...
sum(ix), length(p), N); </langsyntaxhighlight>
 
Output:
<pre> There are 17 Pythagorean Triples and 7 primitive triples with a perimeter smaller than 100.</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that returns a pythagorean triple from two parameters */
pythag(u,v):=[u^2-v^2,2*u*v,u^2+v^2]$
 
/* Predicate function to check for primitivity */
primitivep(lst):=if lreduce('gcd,lst)=1 then true$
 
/* Function that returns perimeter */
perim(lst):=apply("+",lst)$
 
/* Function to return a list of triples by parameter u */
/* Parameter v is controlled to be lesser or equal than u, and when equal are deleted */
param_pythag(n):=block(
create_list(lambda([x,y],pythag(x,y) and x#y)(i,j),i,1,n,j,1,i),
delete(false,%%))$
 
/* Test case */
/* With the function param_pythag as it is some non primitive triples are missing, but not the primitives */
sublist(param_pythag(6),lambda([x],primitivep(x) and perim(x)<=100));
 
 
/* The number of triples, primitive or not, can be recovered from the primitives */
block(
apply(append,makelist(%*i,i,1,8)),
sublist(%%,lambda([x],perim(x)<=100)));
</syntaxhighlight>
{{out}}
<pre>
[[3,4,5],[5,12,13],[15,8,17],[7,24,25],[21,20,29],[9,40,41],[35,12,37]]
 
[[3,4,5],[5,12,13],[15,8,17],[7,24,25],[21,20,29],[9,40,41],[35,12,37],[6,8,10],[10,24,26],[30,16,34],[9,12,15],[15,36,39],[12,16,20],[15,20,25],[18,24,30],[21,28,35],[24,32,40]]
</pre>
 
=={{header|Mercury}}==
Line 2,903 ⟶ 3,438:
From [[List comprehensions]]:
 
<langsyntaxhighlight lang="mercury">
:- module comprehension.
:- interface.
Line 2,926 ⟶ 3,461:
solutions((pred(Triple::out) is nondet :- pythTrip(20,Triple)),Result),
write(Result,!IO).
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="modula3">MODULE PyTriple64 EXPORTS Main;
 
IMPORT IO, Fmt;
Line 2,960 ⟶ 3,495:
i := i * 10;
UNTIL i = 10000000;
END PyTriple64.</langsyntaxhighlight>
 
Output:
Line 2,974 ⟶ 3,509:
===Brute force method===
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">import math
 
// a function to check if three numbers are a valid triple
Line 3,018 ⟶ 3,553:
 
print "Up to a perimeter of " + perimeter + ", there are " + ts
println " triples, of which " + ps + " are primitive."</langsyntaxhighlight>
{{out}}
<pre>3, 4, 5 primitive
Line 3,040 ⟶ 3,575:
 
=={{header|Nim}}==
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}}
<langsyntaxhighlight lang="nim">const u = [[ 1, -2, 2, 2, -1, 2, 2, -2, 3],
[ 1, 2, 2, 2, 1, 2, 2, 2, 3],
[-1, 2, 2, -2, 1, 2, -2, 2, 3]]
Line 3,065 ⟶ 3,601:
newTri([3, 4, 5])
echo "Up to ", maxPeri, ": ", total, " triples, ", prim, " primitives"
maxPeri *= 10</langsyntaxhighlight>
Output:
<pre>Up to 10: 0 triples, 0 primitives
Line 3,077 ⟶ 3,613:
 
=={{header|OCaml}}==
<langsyntaxhighlight OCamllang="ocaml">let isqrt n =
let rec iter t =
let d = n - t*t in
Line 3,109 ⟶ 3,645:
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 ]</langsyntaxhighlight>
Output:
<pre>For perimeters up to 100 there are 17 total and 7 primitive
Line 3,120 ⟶ 3,656:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
; triples generator based on Euclid's formula, creates lazy list
(define (euclid-formula max)
Line 3,149 ⟶ 3,685:
(print max ": " (calculate max)))
(map (lambda (n) (expt 10 n)) (iota 6 1)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,163 ⟶ 3,699:
=={{header|PARI/GP}}==
This version is reasonably efficient and can handle inputs like a million quickly.
<langsyntaxhighlight lang="parigp">do(lim)={
my(prim,total,P);
lim\=1;
Line 3,177 ⟶ 3,713:
[prim,total]
};
do(100)</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program PythagoreanTriples (output);
 
var
Line 3,210 ⟶ 3,746:
maxPeri := maxPeri * 10;
end;
end.</langsyntaxhighlight>
Output (on Core2Duo 2GHz laptop):
<pre>time ./PythagoreanTriples
Line 3,225 ⟶ 3,761:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub gcd {
my ($n, $m) = @_;
while($n){
Line 3,251 ⟶ 3,787:
 
tripel 10**$_ for 1..8;
</syntaxhighlight>
</lang>
{{out}}
<pre>Max. perimeter: 10, Total: 0, Primitive: 0
Line 3,265 ⟶ 3,801:
=={{header|Phix}}==
{{Trans|Pascal}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>atom total, prim, maxPeri = 10
<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>
procedure tri(atom s0, s1, s2)
atom p = s0 + s1 + s2
<span style="color: #008080;">procedure</span> <span style="color: #000000;">tri</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s2</span><span style="color: #0000FF;">)</span>
if p<=maxPeri then
<span style="color: #004080;">atom</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s0</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">s1</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">s2</span>
prim += 1
<span style="color: #008080;">if</span> <span style="color: #000000;">p</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">maxPeri</span> <span style="color: #008080;">then</span>
total += floor(maxPeri/p)
<span style="color: #000000;">prim</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
tri( s0+2*(-s1+s2), 2*( s0+s2)-s1, 2*( s0-s1+s2)+s2);
<span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxPeri</span><span style="color: #0000FF;">/</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
tri( s0+2*( s1+s2), 2*( s0+s2)+s1, 2*( s0+s1+s2)+s2);
<span style="color: #000000;">tri</span><span style="color: #0000FF;">(</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*(-</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*(</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*(</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">-</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">);</span>
tri(-s0+2*( s1+s2), 2*(-s0+s2)+s1, 2*(-s0+s1+s2)+s2);
<span style="color: #000000;">tri</span><span style="color: #0000FF;">(</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*(</span> <span style="color: #000000;">s1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*(</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*(</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">);</span>
end if
<span style="color: #000000;">tri</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*(</span> <span style="color: #000000;">s1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*(-</span><span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*(-</span><span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">s2</span><span style="color: #0000FF;">);</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
while maxPeri<=1e8 do
prim := 0;
<span style="color: #008080;">while</span> <span style="color: #000000;">maxPeri</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">1e8</span> <span style="color: #008080;">do</span>
total := 0;
<span style="color: #000000;">prim</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">;</span>
tri(3, 4, 5);
<span style="color: #000000;">total</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">;</span>
printf(1,"Up to %d: %d triples, %d primitives.\n", {maxPeri,total,prim})
<span style="color: #000000;">tri</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">);</span>
maxPeri *= 10;
<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;">"Up to %d: %d triples, %d primitives.\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">maxPeri</span><span style="color: #0000FF;">,</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">prim</span><span style="color: #0000FF;">})</span>
end while</lang>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,298 ⟶ 3,837:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function gcd($a, $b)
Line 3,334 ⟶ 3,873:
}
 
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';</langsyntaxhighlight>
{{out}}<pre>Up to 100, there are 17 triples, of which 7 are primitive.</pre>
 
=={{header|Picat}}==
===Prolog-style===
{{trans|Prolog}}
<syntaxhighlight lang="picat">main :-
garbage_collect(300_000_000),
Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000],
member(Max, Data),
count_triples(Max, Total, Prim),
printf("upto %d, there are %d Pythagorean triples (%d primitive.)%n", Max, Total, Prim),
fail,
nl.
count_triples(Max, Total, Prims) :-
Ps = findall(S, (triple(Max, A, B, C), S is A + B + C)),
Prims = Ps.len,
Total = sum([Max div P : P in Ps]).
% - between_by/4
between_by(A, B, N, K) :-
C = (B - A) div N,
between(0, C, J),
K = N*J + A.
% - Pythagorean triple generator
triple(P, A, B, C) :-
Max = floor(sqrt(P/2)) - 1,
between(0, Max, M),
Start = (M /\ 1) + 1,
Pm = M - 1,
between_by(Start, Pm, 2, N),
gcd(M, N) == 1,
X = M*M - N*N,
Y = 2*M*N,
C = M*M + N*N,
order2(X, Y, A, B),
(A + B + C) =< P.
order2(A, B, A, B) :- A < B, !.
order2(A, B, B, A).</syntaxhighlight>
 
{{out}}
<pre>upto 100, there are 17 Pythagorean triples (7 primitive.)
upto 1000, there are 325 Pythagorean triples (70 primitive.)
upto 10000, there are 4857 Pythagorean triples (702 primitive.)
upto 100000, there are 64741 Pythagorean triples (7026 primitive.)
upto 1000000, there are 808950 Pythagorean triples (70229 primitive.)
upto 10000000, there are 9706567 Pythagorean triples (702309 primitive.)
upto 100000000, there are 113236940 Pythagorean triples (7023027 primitive.)
 
CPU time 4.612 seconds.</pre>
 
===Another approach===
{{trans|Go}}
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.
 
<syntaxhighlight lang="picat">main =>
foreach(MaxPeri in [10**I : I in 2..8])
[Total, Prim] = newTri(MaxPeri,0,0,3,4,5),
printf("Up to %d: %d triples, %d primitives\n", MaxPeri, Total, Prim)
end.
 
newTri(MaxPeri,Prim,Total,S0, S1, S2) = [PrimRet,TotalRet] =>
P = S0 + S1 + S2,
if P <= MaxPeri then
Prim2 = Prim + 1,
Total2 = Total + MaxPeri div P,
[Prim3,Total3] = newTri(MaxPeri,Prim2,Total2, +1*S0-2*S1+2*S2, +2*S0-1*S1+2*S2, +2*S0-2*S1+3*S2),
[Prim4,Total4] = newTri(MaxPeri,Prim3,Total3, +1*S0+2*S1+2*S2, +2*S0+1*S1+2*S2, +2*S0+2*S1+3*S2),
[Prim5,Total5] = newTri(MaxPeri,Prim4,Total4, -1*S0+2*S1+2*S2, -2*S0+1*S1+2*S2, -2*S0+2*S1+3*S2),
PrimRet = Prim5,
TotalRet = Total5
else
PrimRet = Prim,
TotalRet = Total
end.</syntaxhighlight>
 
{{out}}
<pre>Up to 100: 7 triples, 17 primitives
Up to 1000: 70 triples, 325 primitives
Up to 10000: 703 triples, 4858 primitives
Up to 100000: 7026 triples, 64741 primitives
Up to 1000000: 70229 triples, 808950 primitives
Up to 10000000: 702309 triples, 9706567 primitives
Up to 100000000: 7023027 triples, 113236940 primitives
 
CPU time 4.373 seconds.</pre>
 
===With "global variables"===
Actually, Picat has some support for global variables, using the global available map (<code>get_global_map</code>).
<syntaxhighlight lang="picat">main =>
foreach(MaxPeri in [10**I : I in 2..8])
Map = get_global_map(),
Map.put(max_peri,MaxPeri),
Map.put(prim,0),
Map.put(total,0),
newTri3(3,4,5),
printf("Up to %d: %d triples, %d primitives\n", MaxPeri, Map.get(total), Map.get(prim))
end.
 
newTri2(S0, S1, S2) =>
P = S0 + S1 + S2,
Map = get_global_map(),
if P <= Map.get(max_peri) then
Map.put(prim, Map.get(prim)+1),
Map.put(total,Map.get(total) + Map.get(max_peri) div P),
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),
newTri2(-1*S0+2*S1+2*S2, -2*S0+1*S1+2*S2, -2*S0+2*S1+3*S2)
end.</syntaxhighlight>
 
This version is - however - slower: 7.401s.
 
=={{header|PicoLisp}}==
{{trans|C}}
<langsyntaxhighlight PicoLisplang="picolisp">(for (Max 10 (>= 100000000 Max) (* Max 10))
(let (Total 0 Prim 0 In (3 4 5))
(recur (In)
Line 3,353 ⟶ 4,004:
(recurse
(mapcar '((U) (sum * U In)) Row) ) ) ) ) )
(prinl "Up to " Max ": " Total " triples, " Prim " primitives.") ) )</langsyntaxhighlight>
Output:
<pre>Up to 10: 0 triples, 0 primitives.
Line 3,366 ⟶ 4,017:
=={{header|PL/I}}==
Version 1
<langsyntaxhighlight PLlang="pl/Ii">*process source attributes xref or(!);
/*********************************************************************
* REXX pgm counts number of Pythagorean triples
Line 3,455 ⟶ 4,106:
End;
 
End;</langsyntaxhighlight>
Version 2
<syntaxhighlight lang="pl/i">
<lang PL/I>
pythagorean: procedure options (main, reorder); /* 23 January 2014 */
declare (a, b, c) fixed (3);
Line 3,489 ⟶ 4,140:
end GCD;
 
end pythagorean;</langsyntaxhighlight>
Output:
<pre>
Line 3,500 ⟶ 4,151:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function triples($p) {
if($p -gt 4) {
Line 3,551 ⟶ 4,202:
"There are $(($triples).Count) Pythagorean triples with perimeter no larger than 100
and $(($coprime).Count) of them are coprime."
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 3,558 ⟶ 4,209:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
show :-
Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000],
Line 3,596 ⟶ 4,247:
order2(A, B, A, B) :- A < B, !.
order2(A, B, B, A).
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,620 ⟶ 4,271:
<math>n \le 10,000</math><br /><br />
 
<langsyntaxhighlight lang="purebasic">
 
Procedure.i ConsoleWrite(t.s) ; compile using /CONSOLE option
Line 3,689 ⟶ 4,340:
ConsoleWrite("")
et=ElapsedMilliseconds()-st:ConsoleWrite("Elapsed time = "+str(et)+" milliseconds")
</syntaxhighlight>
</lang>
 
 
Line 3,713 ⟶ 4,364:
=={{header|Python}}==
Two methods, the second of which is much faster
<langsyntaxhighlight lang="python">from fractions import gcd
 
 
Line 3,769 ⟶ 4,420:
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
</syntaxhighlight>
</lang>
 
;Output:
Line 3,829 ⟶ 4,480:
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:<langsyntaxhighlight Pythonlang="python">from sys import setrecursionlimit
setrecursionlimit(2000) # 2000 ought to be big enough for everybody
 
Line 3,842 ⟶ 4,493:
 
for peri in [10 ** e for e in range(1, 8)]:
print peri, triples(peri)</langsyntaxhighlight>Output:<syntaxhighlight lang="text">10 (0, 0)
100 (7, 17)
1000 (70, 325)
Line 3,848 ⟶ 4,499:
100000 (7026, 64741)
1000000 (70229, 808950)
10000000 (702309, 9706567)</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
Based on the method shown in the Mathologer video "Fibonacci = Pythagoras: Help save a stunning discovery from oblivion!". https://youtu.be/94mV7Fmbx88
 
From the first solution "(1, 1, 2, 3)" (in quackery notation <code>[ 1 1 2 3 ]</code>) use functions <code>f1</code>, <code>f2</code>, and <code>f3</code> for recursive depth-first tree traversal. Terminating condition is that perimeter > limit (i.e. 100). At each node add one to the count of primitive pythagorean triples, and n to the count of all pythagorean triples, where n = floor(limit/perimeter).
 
<pre> f1 corresponds to the right hand branch of the tree in the mathologer video
f2 corresponds to the left hand branch...
f3 corresponds to the central branch...
 
a b c d A B C D A B C D
f1 [ 1 1 2 3 ] --> [ 1 2 3 5 ] [ a c A+B B+C ]
f2 [ 1 1 2 3 ] --> [ 3 1 4 5 ] [ d b A+B B+C ]
f3 [ 1 1 2 3 ] --> [ 3 2 5 7 ] [ d c A+B B+C ]
 
a b c d
[ 1 1 2 3 ] --> [ 3 4 5 ] [ a*d 2b*c (b*d)+(a*c) ] pythagorean triple
a*d + 2b*c + b*d + a*c perimeter
= (a*(c+d))+(b*(2c+d))</pre>
 
The recursive part of the word <code>task</code> is
 
<pre> [ dup perimeter
limit share over < iff 2drop done ( end on terminating condition )
1 primitives tally
limit share swap / triples tally
dup f1 recurse
dup f2 recurse
f3 again ]</pre>
 
Note that <code>f3 again</code> is equivalent to <code>f3 recurse</code> but a smidgeon faster by optimising tail-end recursion.
 
The ancillary stacks <code>limit</code>,<code>primitives</code>, and <code>triples</code> can be integer variables in languages that have variables.
 
<syntaxhighlight lang="Quackery"> [ dup 0 peek
swap 2 peek
2dup + 2dup +
join join join ] is f1 ( [ --> [ )
 
[ dup 3 peek
swap 1 peek
2dup + 2dup +
join join join ] is f2 ( [ --> [ )
 
[ dup 3 peek
swap 2 peek
2dup + 2dup +
join join join ] is f3 ( [ --> [ )
 
[ do over + tuck + rot * unrot * + ] is perimeter ( [ --> n )
 
[ stack ] is limit ( --> s )
[ stack ] is primitives ( --> s )
[ stack ] is triples ( --> s )
 
[ limit put
0 primitives put
0 triples put
' [ 1 1 2 3 ]
[ dup perimeter
limit share over < iff 2drop done
1 primitives tally
limit share swap / triples tally
dup f1 recurse
dup f2 recurse
f3 again ]
say "Pythagorean triples, perimeter < "
limit take echo
say ": "
triples take echo
say ", of which "
primitives take echo
say " are primitive." cr ] is task ( n --> )
 
7 times [ 10 i^ 2 + ** task ]</syntaxhighlight>
 
{{out}}
 
<pre>Pythagorean triples, perimeter < 100: 17, of which 7 are primitive.
Pythagorean triples, perimeter < 1000: 325, of which 70 are primitive.
Pythagorean triples, perimeter < 10000: 4858, of which 703 are primitive.
Pythagorean triples, perimeter < 100000: 64741, of which 7026 are primitive.
Pythagorean triples, perimeter < 1000000: 808950, of which 70229 are primitive.
Pythagorean triples, perimeter < 10000000: 9706567, of which 702309 are primitive.
Pythagorean triples, perimeter < 100000000: 113236940, of which 7023027 are primitive.
</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
#| Euclid's enumeration formula and counting is fast enough for extra credit.
Line 3,895 ⟶ 4,633:
113236940, 7023027.
cpu time: 11976 real time: 12215 gc time: 2381
|#</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.09}}
Here is a straight-forward, naivenaïve brute force implementation:
<syntaxhighlight lang="raku" perl6line>constant limit = 100;
 
for [X] [^limit] xx 3 -> (\a, \b, \c) {
say [a, b, c] if a < b < c and a + b + c <= limit and a**2b + b**2b == c**2c
}</langsyntaxhighlight>
{{out}}
<pre style="height:25ex">[3 4 5]
[5 12 13]
[6 8 10]
[7 24 25]
[8 15 17]
[9 12 15]
[9 40 41]
[10 24 26]
[12 16 20]
11 60 61
[12 1635 2037]
[15 20 25]
12 35 37
[15 36 39]
13 84 85
[16 30 34]
14 48 50
[18 24 30]
15 20 25
[20 21 29]
15 36 39
[21 28 35]
16 30 34
[24 32 40]
16 63 65
</pre>
18 80 82
20 21 29
20 48 52
21 28 35
21 72 75
24 32 40
24 45 51
24 70 74
25 60 65
27 36 45
28 45 53
30 40 50
30 72 78
32 60 68
33 44 55
33 56 65
35 84 91
36 48 60
36 77 85
39 52 65
39 80 89
40 42 58
40 75 85
42 56 70
45 60 75
48 55 73
48 64 80
51 68 85
54 72 90
57 76 95
60 63 87
65 72 97</pre>
Here is a slightly less naive brute force implementation, but still not practical for large perimeter limits.
<syntaxhighlight lang="raku" perl6line>my $limit = 10000;
my atomicint $i = 0;
my @triples[$limit/2];
Line 3,970 ⟶ 4,677:
 
say my $result = "There are {+@triples.grep:{$_ !eqv Any}} Pythagorean Triples with a perimeter <= $limit,"
~"\nof which {[+] @triples.grep: so *} are primitive.";</langsyntaxhighlight>
{{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" perl6line>sub triples($limit) {
my $primitive = 0;
my $civilized = 0;
Line 3,994 ⟶ 4,701:
for 10,100,1000 ... * -> $limit {
say triples $limit;
}</langsyntaxhighlight>
Output:
<pre>10 => (0 0)
Line 4,009 ⟶ 4,716:
 
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" perl6line>constant @coeff = [[+1, -2, +2], [+2, -1, +2], [+2, -2, +3]],
[[+1, +2, +2], [+2, +1, +2], [+2, +2, +3]],
[[-1, +2, +2], [-2, +1, +2], [-2, +2, +3]];
Line 4,031 ⟶ 4,738:
for 10, 100, 1000, 10000 -> $limit {
say triples $limit;
}</langsyntaxhighlight>
{{out}}
<pre>10 => (0 0)
Line 4,040 ⟶ 4,747:
=={{header|REXX}}==
===using GCD for determinacy===
<langsyntaxhighlight lang="rexx">/*REXX program counts the number of Pythagorean triples that exist given a maximum */
/*──────────────────── perimeter of N, and also counts how many of them are primitives.*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,065 ⟶ 4,772:
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</langsyntaxhighlight>
{{out|output|text= &nbsp; when using the default input of: &nbsp; &nbsp; <tt> 100 </tt>}}
<pre>
max perimeter = 100 Pythagorean triples = 17 primitives = 7
</pre>
{{out|output|text= &nbsp; when using the default input of: &nbsp; &nbsp; <tt> 1000 </tt>}}
<pre>
max perimeter = 1000 Pythagorean triples = 325 primitives = 70
Line 4,081 ⟶ 4,788:
 
Non-primitive Pythagorean triples are generated after a primitive triple is found.
<langsyntaxhighlight lang="rexx">/*REXX program counts the number of Pythagorean triples that exist given a maximum */
/*──────────────────── perimeter of N, and also counts how many of them are primitives.*/
parse arg N . /*obtain optional argument from the CL.*/
Line 4,109 ⟶ 4,816:
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</langsyntaxhighlight>
{{out|output|text= &nbsp; is identical to the 1<sup>st</sup> REXX version.}}<br><br>
 
{{out|output|text= &nbsp; when using the default input of: &nbsp; &nbsp; <tt> 10000 </tt>}}
<pre>
max perimeter = 10000 Pythagorean triples = 4858 primitives = 703
Line 4,118 ⟶ 4,825:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
size = 100
sum = 0
Line 4,142 ⟶ 4,849:
end
return gcd
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,168 ⟶ 4,875:
=={{header|Ruby}}==
{{trans|Java}}
<langsyntaxhighlight lang="ruby">class PythagoranTriplesCounter
def initialize(limit)
@limit = limit
Line 4,196 ⟶ 4,903:
p [perim, c.total, c.primitives]
perim *= 10
end</langsyntaxhighlight>
 
output
Line 4,209 ⟶ 4,916:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::thread;
 
fn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 {
Line 4,254 ⟶ 4,961:
new_th_1.join().unwrap();
new_th_2.join().unwrap();
}</langsyntaxhighlight>
{{out}}
<pre> Primitive triples below 100 : 7
Line 4,283 ⟶ 4,990:
=={{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)].
<langsyntaxhighlight Scalalang="scala">object PythagoreanTriples extends App {
 
println(" Limit Primatives All")
Line 4,307 ⟶ 5,014:
println(f"a + b + c <= ${limit.toFloat}%3.1e $primCount%9d $tripCount%12d")
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Gauche Scheme}}
<langsyntaxhighlight Schemelang="scheme">(use srfi-42)
 
(define (py perim)
Line 4,322 ⟶ 5,029:
(begin (when (= 1 (gcd a b)) (inc! prim)))
1)
prim))</langsyntaxhighlight>
<b>Testing:</b>
<pre>
Line 4,341 ⟶ 5,048:
The example below uses [http://seed7.sourceforge.net/libraries/bigint.htm bigInteger] numbers:
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigint.s7i";
 
Line 4,371 ⟶ 5,078:
max_peri *:= 10_;
end while;
end func;</langsyntaxhighlight>
 
Output:
Line 4,387 ⟶ 5,094:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func triples(limit) {
var primitive = 0
var civilized = 0
Line 4,407 ⟶ 5,114:
for n (1..Inf) {
say triples(10**n)
}</langsyntaxhighlight>
 
{{out}}
Line 4,422 ⟶ 5,129:
=={{header|Swift}}==
{{trans|Pascal}}
<langsyntaxhighlight Swiftlang="swift">var total = 0
var prim = 0
var maxPeri = 100
Line 4,444 ⟶ 5,151:
print("Up to \(maxPeri) : \(total) triples \( prim) primitives.")
maxPeri *= 10
}</langsyntaxhighlight>
 
{{out}}
Line 4,460 ⟶ 5,167:
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! -->
<langsyntaxhighlight lang="tcl">proc countPythagoreanTriples {limit} {
lappend q 3 4 5
set idx [set count [set prim 0]]
Line 4,484 ⟶ 5,191:
lassign [countPythagoreanTriples $i] count primitive
puts "perimeter limit $i => $count triples, $primitive primitive"
}</langsyntaxhighlight>
Output:
<pre>
Line 4,497 ⟶ 5,204:
 
=={{header|VBA}}==
{{trans|Pascal}}<langsyntaxhighlight lang="vb">Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
Line 4,518 ⟶ 5,225:
maxPeri = maxPeri * 10
Loop
End Sub</langsyntaxhighlight>{{out}}
<pre>Up to 100 : 17 triples, 7 primitives.
Up to 1000 : 325 triples, 70 primitives.
Line 4,529 ⟶ 5,236:
=={{header|VBScript}}==
{{trans|Perl}}
<syntaxhighlight lang="vb">
<lang vb>
For i=1 To 8
WScript.StdOut.WriteLine triples(10^i)
Line 4,566 ⟶ 5,273:
Loop
End Function
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic}}==
Line 4,575 ⟶ 5,282:
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
<langsyntaxhighlight lang="vb">Option Explicit
 
Dim total As Long, prim As Long, maxPeri As Long
Line 4,602 ⟶ 5,309:
maxPeri = maxPeri * 10
Loop
End Sub</langsyntaxhighlight>
{{out}}
<pre>Up to 100 : 17 triples, 7 primitives.
Line 4,615 ⟶ 5,322:
{{trans|Go}}
Limited to a maximum perimeter of 10 billion in order to finish in a reasonable time.
<langsyntaxhighlight ecmascriptlang="wren">var sc = System.clock
var total = 0
var prim = 0
Line 4,624 ⟶ 5,331:
var p = s0 + s1 + s2
if (p <= maxPeri) {
prim = prim + 1
total = total + (maxPeri/p).floor
System.write("") // fixes a VM recursion bug
newTri.call( 1*s0-2*s1+2*s2, 2*s0-1*s1+2*s2, 2*s0-2*s1+3*s2)
newTri.call( 1*s0+2*s1+2*s2, 2*s0+1*s1+2*s2, 2*s0+2*s1+3*s2)
Line 4,638 ⟶ 5,344:
total = 0
newTri.call(3, 4, 5)
var secs = (System.clock - sc).round
System.print("Up to %(maxPeri): %(total) triples, %(prim) primitives, %(secs) seconds")
maxPeri = 10 * maxPeri
}</langsyntaxhighlight>
 
{{out}}
Timings are for an Intel Core i7-8565U machine running Wren 0.24.0 on Ubuntu 1820.04.
<pre>
Up to 100: 17 triples, 7 primitives, 0 seconds
Line 4,651 ⟶ 5,357:
Up to 100000: 64741 triples, 7026 primitives, 0 seconds
Up to 1000000: 808950 triples, 70229 primitives, 0 seconds
Up to 10000000: 9706567 triples, 702309 primitives, 10 seconds
Up to 100000000: 113236940 triples, 7023027 primitives, 54 seconds
Up to 1000000000: 1294080089 triples, 70230484 primitives, 5145 seconds
Up to 10000000000: 14557915466 triples, 702304875 primitives, 554463 seconds
</pre>
 
=={{header|XPL0}}==
Simple minded algorithm:
<syntaxhighlight lang="xpl0">func GCD(N, D); \Return the greatest common divisor of N and D
int N, D, R; \numerator and denominator
[if D > N then
[R:=D; D:=N; N:=R];
while D > 0 do
[R:= rem(N/D);
N:= D;
D:= R;
];
return N;
];
 
int Max, PrimCnt, TripCnt, M, N, A, B, C, K, Prim;
[Max:= 10;
repeat PrimCnt:= 0; TripCnt:= 0;
for M:= 2 to Max do
for N:= 1 to M do
[if GCD(M,N) = 1 \coprime\ and
((M&1) = 0 xor (N&1) = 0) \one even\ then
[A:= M*M - N*N;
B:= 2*M*N;
C:= M*M + N*N;
Prim:= A+B+C;
if Prim <= Max then PrimCnt:= PrimCnt+1;
for K:= Max/Prim downto 1 do
if K*Prim <= Max then TripCnt:= TripCnt+1;
];
];
Format(6, 0);
Text(0, "Up to"); RlOut(0, float(Max));
RlOut(0, float(TripCnt)); Text(0, " triples,");
RlOut(0, float(PrimCnt)); Text(0, " primitives.^m^j");
Max:= Max*10;
until Max > 10_000;
]</syntaxhighlight>
 
{{out}}
<pre>
Up to 10 0 triples, 0 primitives.
Up to 100 17 triples, 7 primitives.
Up to 1000 325 triples, 70 primitives.
Up to 10000 4858 triples, 703 primitives.
</pre>
 
{{trans|Go}}
<syntaxhighlight lang="xpl0">int Total, Prim, MaxPeri;
proc NewTri(S0, S1, S2);
int S0, S1, S2, P;
[P:= S0 + S1 + S2;
if P <= MaxPeri then
[Prim:= Prim+1;
Total:= Total + MaxPeri/P;
NewTri(+1*S0-2*S1+2*S2, +2*S0-1*S1+2*S2, +2*S0-2*S1+3*S2);
NewTri(+1*S0+2*S1+2*S2, +2*S0+1*S1+2*S2, +2*S0+2*S1+3*S2);
NewTri(-1*S0+2*S1+2*S2, -2*S0+1*S1+2*S2, -2*S0+2*S1+3*S2);
];
];
[MaxPeri:= 10;
while MaxPeri <= 100_000_000 do
[Prim:= 0;
Total:= 0;
NewTri(3, 4, 5);
Format(10, 0);
Text(0, "Up to"); RlOut(0, float(MaxPeri)); Text(0, ":");
RlOut(0, float(Total)); Text(0, " triples,");
RlOut(0, float(Prim)); Text(0, " primitives.^m^j");
MaxPeri:= MaxPeri*10;
];
]</syntaxhighlight>
 
{{out}}
<pre>
Up to 10: 0 triples, 0 primitives.
Up to 100: 17 triples, 7 primitives.
Up to 1000: 325 triples, 70 primitives.
Up to 10000: 4858 triples, 703 primitives.
Up to 100000: 64741 triples, 7026 primitives.
Up to 1000000: 808950 triples, 70229 primitives.
Up to 10000000: 9706567 triples, 702309 primitives.
Up to 100000000: 113236940 triples, 7023027 primitives.
</pre>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn tri(lim,a=3,b=4,c=5){
p:=a + b + c;
if(p>lim) return(0,0);
Line 4,667 ⟶ 5,459:
tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c)
);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">n:=10; do(10){ println("%,d: %s".fmt(n,tri(n).reverse())); n*=10; }</langsyntaxhighlight>
{{out}}
<pre>10: L(0,0)
Line 4,701 ⟶ 5,493:
Set in line nr: 11 IF L<=1000 THEN GO TO 2
 
<langsyntaxhighlight lang="zxbasic"> 1 LET Y=0: LET X=0: LET Z=0: LET V=0: LET U=0: LET L=10: LET T=0: LET P=0: LET N=4: LET M=0: PRINT "limit trip. prim."
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 4,711 ⟶ 5,503:
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</langsyntaxhighlight>
{{out}}
<pre>limit trip. prim.
9,476

edits