| Bytes | Lang | Time | Link |
|---|---|---|---|
| 057 | Perl 5 a | 250402T211613Z | Xcali |
| 128 | Pascal | 250401T120002Z | Kai Burg |
| 048 | Julia | 230817T204130Z | Ashlin H |
| 010 | Thunno 2 | 230816T123109Z | The Thon |
| 035 | APL Dyalog Classic | 211026T170200Z | Logan Ma |
| 067 | Python 3 | 211026T073154Z | Jitse |
| 009 | Jelly | 211018T063747Z | Bubbler |
| 028 | K ngn/k | 211025T214939Z | Traws |
| 050 | R | 211019T134152Z | Giuseppe |
| 090 | Excel | 211019T165333Z | Engineer |
| 086 | Excel | 211019T224701Z | Axuary |
| 087 | Swift | 211019T184754Z | Cristik |
| 045 | Raku | 211019T175058Z | Sean |
| 083 | Kotlin | 211019T151849Z | Trenton |
| 074 | C clang | 211018T105816Z | Noodle9 |
| 039 | Wolfram Language Mathematica | 211018T080229Z | theorist |
| 065 | R | 211018T110739Z | Dominic |
| 053 | Ruby | 211018T113330Z | AZTECCO |
| 034 | TIBasic | 211018T153208Z | MarcMush |
| 046 | Haskell | 211018T193853Z | AZTECCO |
| 131 | Batch | 211018T184351Z | Neil |
| 179 | Alchemist | 211018T181931Z | Nitrodon |
| 038 | APL Dyalog Classic | 211018T095746Z | wasif |
| 016 | Brachylog | 211018T165507Z | DLosc |
| 012 | Gaia | 211018T145842Z | ovs |
| 091 | Java | 211018T142606Z | Unmitiga |
| 028 | APLDyalog Unicode | 211018T131420Z | ovs |
| 042 | APL+WIN | 211018T114941Z | Graham |
| 055 | JavaScript V8 | 211018T104648Z | Arnauld |
| 024 | Charcoal | 211018T100434Z | Neil |
| 083 | Retina 0.8.2 | 211018T095755Z | Neil |
| 014 | 05AB1E | 211018T072136Z | wasif |
| 010 | Vyxal | 211018T071439Z | Bubbler |
| 057 | JavaScript V8 | 211018T074852Z | tsh |
| nan | Python 3.8 prerelease | 211018T063256Z | m90 |
| 017 | Vyxal | 211018T064417Z | lyxal |
| 022 | Vyxal | 211018T063746Z | emanresu |
| 047 | Wolfram Language Mathematica | 211018T062631Z | alephalp |
Pascal, 128 B
This program simply tests whether sum of the squares over the legs equal the square over the hypotenuse for any leg shorter than or equal to the hypotenuse.
To eliminate duplicates the nested for‐loop does not start at 1.
program p(input,output);var a,b,c:integer;begin
read(c);for a:=1 to c do for b:=a to c do if a*a+b*b=c*c then writeLn(a,b,c)end.
Normalized:
program pythagoreanTriplesGivenTheHypotenuse(input, output);
type
sideLength = 1‥trunc(sqrt(maxInt));
var
hypotenuse, legA, legB: sideLength;
begin
{ It is not necessary to specify `input`. If omitted, `input`
is the default source file. Since the data type of `hypotenuse`
is `sideLength`, the `program` aborts unless a positive `integer`
has been entered. }
readLn(input, hypotenuse);
{ In Pascal `for`‐loop limits are inclusive. Since the legs are
are guaranteed to be shorter than the hypotenuse, it does not
make sense to test whether hypotenuse² + b² = hypotenuse².
The golfed version does not use this optimization, though. }
for legA ≔ 1 to pred(hypotenuse) do
begin
for legB ≔ legA to pred(hypotenuse) do
begin
{ Like in mathematics, in Pascal a single `=` indicates
a comparison. `≔` is used to actually modify variables. }
if sqr(legA) + sqr(legB) = sqr(hypotenuse) then
begin
writeLn(legA, legB, hypotenuse)
end
end
end
{ In Pascal semicolons are used to separate statements, not to
conclude them. Note their absence in the preceding lines. }
end.
To achieve a nice tabular look the implementation‐defined default minimum printing width for integer values to a text file (like output) should be a reasonable value.
Sample input:
1105
Sample output:
47 1104 1105
105 1100 1105
169 1092 1105
264 1073 1105
272 1071 1105
425 1020 1105
468 1001 1105
520 975 1105
561 952 1105
576 943 1105
663 884 1105
700 855 1105
744 817 1105
Julia, 48 bytes
~c=[[a,b,c] for b=1:c for a=1:b if a^2+b^2==c^2]
Another variation turns out to be a byte longer:
~c=[[a,b,c] for b=1:c,a=1:c if a<b&&a^2+b^2==c^2]
Thunno 2, 10 bytes
2Ṛȷaæ²DS½Ƈ
Explanation
2Ṛȷaæ²DS½Ƈ # Implicit input
2Ṛ # Combinations with length 2
ȷa # Append input to each pair
æ # Filter this list by:
² # Square each value
D # Duplicate
S½ # Half of the sum
Ƈ # Is in the list?
# Implicit output
APL (Dyalog Classic), 35 bytes
{⍵,⍨¨{⍵↑⍨2÷⍨≢⍵}⍸(⍵*2)=+/¨2*⍨∘.,⍨⍳⍵}
Calculates every combination of a^2 + b^2 and stores the values which add up to c^2
Python 3, 67 bytes
lambda n:[(j,i,n)for i in range(n)for j in range(i)if i*i+j*j==n*n]
Jelly, 10 9 bytes
ŒcÆḊ=¥Ƈ;€
Backport of my improved Vyxal answer to use pairs without replacement. -1 byte because I just realized there's a 2-byte norm built-in that saves a square. Passes all small test cases and moderately large ones (like 850) but 1105 times out, and might not work for larger inputs due to floating-point errors.
How it works
ŒcÆḊ=¥Ƈ;€ Monadic link; Input = n, the hypotenuse
Œc Pairs of 1..n without replacement
ÆḊ=¥Ƈ Filter those whose norm (sqrt of self-dot-product) equals n
;€ Append n to each pair
Jelly, 11 bytes
R²+²)=²ŒṪ;€
How it works
R²+²)=²ŒṪ;€ Monadic link; Input = n, the hypotenuse
) For each number i of 1..n,
R²+² collect the values of j^2+i^2 for j in 1..i
=²ŒṪ Coordinates (i,j) where j^2+i^2 = n^2
(only gives the coordinates where i>j)
;€ Append n to each pair
K (ngn/k), 28 bytes
{+x,+(x=%+/*/2#,+:)#+&~|\=x}
It uses the indices of ones in an upper triangular matrix for creating all possible (a,b) pairs, then filters them based on the pythagorean condition. Prepends the hipotenuse for each pair found.
R, 53 50 bytes
rbind(x<-scan(),p<-combn(x,2))[,colSums(p^2)==x^2]
Thanks to Dominic van Essen and pajonk in the comments for some golf ideas; and thanks to Dominic van Essen and thothal for -3 bytes together.
Returns a (possibly empty) matrix with triples as columns.
Equivalent to (among others) ovs' Gaia answer.
x=scan() # read input
pairs=combn(1:x,2) # pairwise combinations of 1..x, as columns of a matrix
triple <- colSums(pairs^2)==x^2 # is it a triple?
rbind(pairs,x)[,triple] # add a row of x's and filter the columns by the triple condition
Excel, 100 93 90 bytes
=LET(a,SEQUENCE(A1),b,TRANSPOSE(a),CONCAT(IF((a<b)*(a^2+b^2)-A1^2,"",a&","&b&","&A1&"
")))
Input is in A1. Triples are delimited by a comma and each triple is separated by a new line with a trailing new line. The LET() and SEQUENCE() functions are only available in certain versions of Excel.
LET() allows us to define variables and reference them later. This goes a long way towards saving bytes. The final parameter doesn't define a variable and instead is the output result.
a,SEQUENCE(c) creates a 1D array of numbers from 1 to the input.
b,TRANSPOSE(a) creates the same array as a except transposed. This lets us work with a matrix of axb so we can evaluate all possible combinations of integers less than or equal to the input.
CONCAT(IF((a>b)*(a^2+b^2)-A1^2,"",a&","&b&","&A1&"
"))
This is where all the calculation and concatenation happens so I'll break it into pieces.
(a>b)*(a^2+b^2)-A1^2 does the math bit to check if it's a triple and, thanks to (a>b), ignores half the results so we don't have duplicates. You cannot have a Pythagorean triple where a=b so this is an OK filter. We can use (~)-A1^2 instead of (~)<>A1^2 since Excel will interpret 0 as False and any non-zero number as True.
a&","&b&","&A1&"\n" (where \n is a literal line break in the original formula) creates a text string in the format a,b,A1 with a trailing new line. These are the results that show up at the end.
CONCAT(IF(~,"",~)) combines all the results into one big string. Those results are either triples with a trailing new line or blank text. This is what creates the final output.
Excel, 86 bytes
=LET(a,SEQUENCE(A1/2^0.5),b,(A1^2-a^2)^0.5,CONCAT(IF(MOD(b,1),"",a&","&b&","&A1&"
")))
a equals the sequence of numbers up to the hypotenuse / \$\sqrt2\$.
b equals the list of numbers that makes a Pythagorean triple with the corresponding number in a.
If mod(b,1) = 0 then return the triple otherwise return blank.
Swift, 87 bytes
let p={n in(1...n).reduce(into:[]){for j in $1...n{if $1*$1+j*j==n*n{$0+=[[$1,j,n]]}}}}
Using the reduce instead of the outer for loop to save the bytes needed to declare the result variable, and to return it.
Raku, 45 bytes
{grep *²+*²==*²,flat .&combinations(2)X$_}
$_is the hypotenese length, the argument to the function..&combinations(2)is a list of all two-element combinations of the list of integers from zero to one less than the hypoteneuse. These are the possible triangle leg lengths. (The unusual syntax.&means to call the global function namedcombinations, passing$_as the first parameter. It saves a few bytes here.)X $_pastes the hypoteneuse onto the end of each combination using the cross-product operatorX.flatflattens the list.*² + *² == *²is an anonymous function that returns true if the sum of the squares of its first two arguments is equal to the square of the third argument.grepconsumes three elements at a time from the flattened list of side lengths (since its test function takes three arguments) and returns the triples that describe a right triangle.
Kotlin, 83 bytes
fun x(c:Int){for(i in 1..c)for(j in 1..i)if(i*i+j*j==c*c)print("[${j} ${i} ${c}]")}
C (clang), 99 \$\cdots\$ 75 74 bytes
a;b;f(c){for(b=c;a=--b;)for(;--a;)c*c-b*b-a*a||printf("%d,%d,%d ",a,b,c);}
Saved a byte thanks to ceilingcat!!!
Inputs integer \$c\$ and outputs all unique Pythagorean triples with hypotenuse \$c\$. The side lengths are separated by commas and the Pythagorean triples separated by spaces.
Wolfram Language (Mathematica), 41 40 39 bytes
Solve[a^2+b^2==c#>c==#>b>a>0,Integers]&
-1 byte from ovs
-1 byte from att
Integers restricts it to integers; >0 restricts it to positive integers; and b>a removes the duplicates. c# is c^2; c==# adds the input to each solution set (as required by the OP).
Alternately (also 39 bytes):
Solve[Norm@{a,b}==c==#>b>a>0,Integers]&
Here's a more verbose version that's similar to the first approach:
Solve[{a^2+b^2==#^2,c==#,b>a>0},Integers]&
R, 71 65 bytes
y=x=scan();while(y<-y-1)(z=(x^2-y^2)^.5)%%1||z>y&&print(c(x,y,z))
Or R >4.1 using recursive function: 64 bytes
(thanks to pajonk for pointing-this out!)
t=\(x,y=1,z=(x^2-y^2)^.5)if(z>y){z%%1||print(c(x,y,z));t(x,y+1)}
Ruby, 67 65 53 bytes
->c{c.times{|a|a.times{|b|p [b,a,c]if a*a+b*b==c*c}}}
- Thanks to @Dingus suggestion to print directly instead of yielding to a return array.
- Switched to a double #times structure surprisingly better than #combination.
r=[] - return array
[*1..c].combination(2) - combinations of 1..input , since a,b are coprime we don't need a==b
{|a,b|r<<[a,b,c] - we add to r the pair yelded with input attached to it
if a*a+b*b==c*c} - if it's a valid triangle
;r} - finally we return r
TI-Basic, 34 bytes
Prompt C
For(A,1,C/√(2
√(C²-A²
If not(fPart(Ans
Disp {A,Ans,C
End
Haskell, 46 bytes
f c=[[a,b,c]|a<-[1..c],b<-[a..c],a*a+b*b==c*c]
- List comprehension made of all combinations a<-[1..c],b<-[a..c] with our Pythagorean condition as guard.
We addcto the pair yelded.
Batch, 131 bytes
@for /l %%b in (1,1,%1)do @for /l %%a in (1,1,%%b)do @call:c %%a %%b %1
@exit/b
:c
@set/ah=%1*%1+%2*%2-%3*%3
@if %h%==0 echo %*
Takes input as a command-line parameter and outputs each triple of space-separated values on its own line. Explanation:
@for /l %%b in (1,1,%1)do
Try all values of b between 1 and c.
@for /l %%a in (1,1,%%b)do
Try all values of a between 1 and b.
@call:c %%a %%b %1
Pass the values to a subroutine so that they can be calculated in separate statements.
@exit/b
Exit the script.
:c
Start the subroutine.
@set/ah=%1*%1+%2*%2-%3*%3
Calculate the difference between the sums of squares and the square of the input.
@if %h%==0 echo %*
If it's zero then output the triple.
Alchemist, 179 bytes
_->In_n+f
f+n->f+b+c+m
f+0n->j
j+a->j+d+x
j+m+0a->k+d
k+d->k+a+x
k+0d->i
0q+b+x->e
0q+0b+e+m->q
q+e+x->q+b
q+0e->
i+0x+0e->j+Out_a+Out_" "+Out_b+Out_" "+Out_c+Out_"\n"
i+0x+e->j+e
a, d, i, j, and k define a source of x, while b, e, and q define a sink for x. m is equal to \$b - a\$ where relevant, and the program halts when it reaches zero to avoid duplicating triples.
Initialization
_->In_n+f
f+n->f+b+c+m
f+0n->j
Simply sets b, c, and m to the input, puts the sink in state j, and puts the source in state 0q.
Source
j+a->j+d+x
j+m+0a->k+d
k+d->k+a+x
k+0d->i
When the source is in state j, this adds \$2a+1\$ x atoms while incrementing \$a\$ (using up an m), then returns to state i. Whenever the source is in state i, it has provided a total of \$a^2\$ x atoms.
Sink
0q+b+x->e
0q+0b+e+m->q
q+e+x->q+b
q+0e->
Similar to the source, but without a special i state. The source starts in state 0q, and in each cycle, it uses up \$2b-1\$ x atoms, decrements \$b\$, and uses up an m. While there is no special state to denote whether the number of atoms taken is equal to \$c^2 - b^2\$, the condition e=0 will work.
Output
The source waits for there to be no more x atoms before starting another cycle; without this check, it could pass every triple without detecting them. This is the purpose of the i state.
i+0x+0e->j+Out_a+Out_" "+Out_b+Out_" "+Out_c+Out_"\n"
i+0x+e->j+e
When there are no more x atoms in the i state, we check whether we are actually at a triple. If we are, output the triple. Either way, move the source to the j state without changing anything else.
APL (Dyalog Classic), 38 bytes
{,∘⍵¨k[⍸(⍵*2)=+/¨2*⍨k←∪,{⍵[⍋⍵]}¨⍳⍵ ⍵]}
-10 thanks to @ovs!!!!
dfn, takes the hypotenuse on right
Brachylog, 20 18 16 bytes
^₂~+Ċ√ᵐℕ₁ᵐ≤₁,?ẉ⊥
Outputs one triple per line. Try it online!
Explanation
^₂~+Ċ√ᵐℕ₁ᵐ≤₁,?ẉ⊥
^₂ The input number squared
~+ is the sum of
Ċ a list of two elements
√ᵐ Get the square root of each element
ℕ₁ᵐ Each of those must be a natural number greater than or equal to 1
≤₁ and they must be sorted in ascending order
,? Append the original input to that list
ẉ and output it with a trailing newline
⊥ Fail unconditionally, forcing Brachylog to backtrack and find
the next output
Gaia, 12 bytes
s¦e⁻+
┅r+¦↑⁈
s¦e⁻+ -- helper function; check whether 3 numbers form a pythagorean triple
s¦ -- square each number -> [a^2 b^2 c^2]
e -- dump all values on the stack -> a^2 b^2 c^2
⁻+ -- subtract and add -> a^2+(b^2-c^2)
┅ -- range from 1 to input
r -- all pairs of values from this list
+¦ -- append the input to each pair
↑⁈ -- Reject; Only keep elements where the above function returns 0
Java, 91 bytes
c->{for(int i=c,j;--i>0;)for(j=i;--j>0;)if(i*i+j*j==c*c)System.out.println(j+" "+i+" "+c);}
APL(Dyalog Unicode), 28 bytes
(,/(+/=2×⊃)¨⍤×⍨⊆⊢)⊢,¨∘⍸⍳∘.<⍳
APL (Dyalog Extended), 39 35 bytes
Longer with the Extended variant, but this one runs in linear time.
{⍵,¨1↑2 ¯1⍴(⌽,¨⊢)⍸0=1|√⍵-⍥(×⍨)⍳⍵-1}
APL+WIN, 42 Bytes
Prompts for hypotenuse:
(((c*2)=+/¨n*2)/n←(,m∘.<m)/,m∘.,m←⍳c),¨c←⎕
JavaScript (V8), 55 bytes
Prints the triples.
n=>{for(q=n;p=--q;)for(;--p;)p*p+q*q-n*n||print(p,q,n)}
Charcoal, 24 bytes
NθFθFι¿⁼×θθ⁺×ιι×κκI⟦⟦κιθ
Try it online! Link is to verbose version of code. Explanation:
Nθ
Input c.
Fθ
Loop b from 0 to c.
Fι
Loop a from 0 to b.
¿⁼×θθ⁺×ιι×κκ
If this is a triple, ...
I⟦⟦κιθ
... output a, b and c on separate lines, double-spacing each triple.
Retina 0.8.2, 83 bytes
^
$'$*_
_
$'$*_
(?<=^((_(?(2)\2_))+))(?=\1)(?=(_(?(3)\3_))+(\d+)$)
¶$#2,$#3,$4¶
A`_
Try it online! Link includes faster test cases. Explanation:
^
$'$*_
Prefix c _s to c.
_
$'$*_
Replace each c with c _s, thus creating c².
(?<=^((_(?(2)\2_))+))
Match at any position which is a positive square number...
(?=\1)
... that is no more than half of c²...
(?=(_(?(3)\3_))+(\d+)$)
... where the difference with c² is also square, and match c while we're there, ...
¶$#2,$#3,$4¶
... and insert the discovered triple.
A`_
Delete everything else.
66 bytes in Retina 1:
.+
*
_
$=
L$v`(?<=^((_(?(2)\2_))+))(?=\1)(_(?(3)\3_))+$
$#2,$#3,$+
Try it online! No test suite due to the program's use of history. Explanation:
.+
*
_
$=
Convert the input to unary and square it.
L$v`(?<=^((_(?(2)\2_))+))(?=\1)(_(?(3)\3_))+$
Match all square suffixes which are greater than their square prefixes, ...
$#2,$#3,$+
... and output the resulting triple.
05AB1E, 14 bytes
L2.ÆʒnOInQ}εIª
Second solution, just replace some boilerplate with sleek 2.Æ (pairs without replacement), also this one is both the shortest and fastest among three
05AB1E, 14 bytes (Thanks to @ovs)
Lã€{ÙʒnOtQ}εIª
05AB1E, 14 bytes
nÅœ2ùʒŲP}tεIª
This is slower, but 2 bytes shorter.
n # square
Ŝ # integer partitions
2ù # keep length 2s
ʒ # filter by
Ų # perfect square?
P # product
} # end filter
t # root
ε # foreach
I # input
ª # tuck
05AB1E, 16 bytes
LDâ€{ÙʒnOInQ}εIª
The most obvious approach
L # 1..n
D # dup
â # cartesian product
€ # vectorize
{ # sort
Ù # nub
ʒ # filter by
n # square each
O # sum
I # input
n # squared
Q # equals?
} # end filter
ε # foreach
I # input
ª # append
Vyxal, 11 10 bytes
ɾ2ḋvp'²ḣ∑=
-1 byte thanks to @lyxal
Thanks for the offer @lyxal, but nah, I don't need flags.
ɾ2ḋvp'²ḣ∑= Full program, input: n, the hypotenuse
ɾ 1..n
2ḋ All pairs (2-combinations) without replacement
vp Prepend n to each pair
' Filter those which satisfy...
² Square each number
ḣ∑= Does the sum of last two equal the first?
Vyxal, 15 bytes
ɾ:Ẋ's=*²∑⁰²=;vJ
Kinda port of my own Jelly answer, using filter instead of "truthy n-D indices".
ɾ:Ẋ's=*²∑⁰²=;vJ Full program, input: n, the hypotenuse
ɾ:Ẋ All pairs between 1..n and 1..n
' ; Filter the pairs where...
s=* it is sorted and
²∑⁰²= the sum of square is equal to n squared
vJ Append n to each pair
JavaScript (V8), 57 bytes
n=>(g=i=>(j=(n*n-++i*i)**.5)>i&&g(i,j%1||print(i,j,n)))``
A quite straightforward approach.
Python 3.8 (pre-release), 68 67 65 bytes
lambda c:[(a,b,c)for a in range(1,c)if(b:=(c*c-a*a)**.5)==b//1>a]
-1 by observing that a and b are never equal in a Pythagorean triple.
-2 thanks to G B, by squaring by self-multiplying.
Vyxal, 18 17 bytes
²Ṅ'Ḣ₃;'∆²A;:[√⌊vJ
It times out for inputs greater than 7, but the algorithm works. I can't wait to be outgolfed by anyone with greater mathematical knowledge lol ;p
-1 thanks to @EmanresuA and their tip from here
Explained
²Ṅ'Ḣ₃;'∆²A;:[√⌊vJ
²Ṅ # from all the integer partitions of the input squared,
'Ḣ₃; # only keep those where the length is 2. And from those,
'∆²A; # only keep those where all numbers are perfect squares.
:[ # If that isn't empty,
√⌊vJ # get the square root of each item, and append the hypotenuse to each sublist.
Vyxal, 22 bytes
ɾ:vɾZƛ÷v";f2ẇ'²∑⁰²=;vJ
What a horrible mess. I'm sure there's so many shorter ways of doing this...
Wolfram Language (Mathematica), 47 bytes
Cases[Range@#~Subsets~{2},x_/;x.x==#^2:>{x,#}]&

