# Pythagorean triples given the hypotenuse

## Definition (from Wikipedia)

A Pythagorean triple consists of three positive integers a, b, and c, such that a² + b² = c².

The typical example of a Pythagorean triple is (3,4,5): 3² + 4² = 9 + 16 = 25 which is 5²

Given an integer number c, write a program or function that returns the list of pythagorean triples where c is the hypotenuse.

The triples do not need to be primitive.

For example: if c=10, the answer will be [[6,8,10]]

## Input:

An integer number, the hypotenuse of the possible triples

## Output:

A list of triples, eventually empty. Order is not important, but the list must be duplicate-free ([3,4,5] and [4,3,5] are the same triple, only one must be listed)

Test cases:

5    -> [[3,4,5]]
7    -> []          # Empty
13   -> [[5,12,13]]
25   -> [[7,24,25],[15,20,25]]
65   -> [[16,63,65],[25,60,65],[33,56,65],[39,52,65]]
1105 -> [[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]]


This is , shortest entry for each language wins.

• Can we output only a and b in each tuple, or do we have to append the input to each? Oct 18, 2021 at 7:04
• @pxeger: You must print (or return) the whole triples.
– G B
Oct 18, 2021 at 9:09

# Vyxal, 11 10 bytes

ɾ2ḋvp'²ḣ∑=


Try it Online!

-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


Try it Online!

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


# Wolfram Language (Mathematica), 4140 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]&


Try it online!

• 40 bytes with Norm.
– ovs
Oct 18, 2021 at 9:22
• 39 bytes
– att
Oct 18, 2021 at 22:27

# Excel, 10093 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.

• You can save 2 bytes by not declaring c = A1 and another byte by replacing the <> with a -. Oct 19, 2021 at 22:40
• @Axuary It ended up saving 3 bytes. Declaring c=A1 made sense in the 100 bytes version of the formula and I failed to re-check that when I cut it down. Thanks. Oct 20, 2021 at 13:07

f c=[[a,b,c]|a<-[1..c],b<-[a..c],a*a+b*b==c*c]


Try it online!

• List comprehension made of all combinations a<-[1..c],b<-[a..c] with our Pythagorean condition as guard.
We add c to the pair yelded.

# Ruby, 67 65 53 bytes

->c{c.times{|a|a.times{|b|p [b,a,c]if a*a+b*b==c*c}}}


Try it online!

• 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

• 58 bytes by printing the triples instead of storing them. Oct 18, 2021 at 22:14
• I wish I could shorten this more interesting 60 byter using complex numbers but I can't see how. Oct 18, 2021 at 22:16
• Thanks for all the help @Dingus, I like the Complex solution, very interesting, that's unfortunate it costs so many bytes Oct 18, 2021 at 23:48
• Nice work with the double times. It's amazing how easy it is to get tunnel vision and miss simple solutions sometimes! Oct 18, 2021 at 23:55
• Thanks @Dingus! I say Ruby is really fun to golf, there are many options with a nice and pleasant syntax. Oct 19, 2021 at 0:07

# 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))


Try it online!

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)}


Try it online!

• Worth noting, that the second approach is shorter in R>=4.1 with 64 bytes by replacing function with \. Oct 18, 2021 at 16:49
• this is incredibly close at 64 but fails for input like 10 or 7. Oct 18, 2021 at 18:23
• @pajonk - I think a slight modification to the fixed version, to make it a full program, is probably Ok: It correctly outputs nothing for an input of 7, even if it then exits with an error. See here. Oct 19, 2021 at 6:14
• @Giuseppe - see ^ Oct 19, 2021 at 6:15
• @pajonk and @ Dominic thanks for the ideas! It's been a while (5 months!) since I've done any golfing, but I found another, shorter approach and posted that instead. Oct 19, 2021 at 13:44

# R, 53 50 bytes

rbind(x<-scan(),p<-combn(x,2))[,colSums(p^2)==x^2]


Try it online!

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

• 1 byte less if you rearrange a bit... Oct 19, 2021 at 20:43
• -3 bytes You do not need : and apply Dominic's hint Oct 21, 2021 at 12:21
• @thothal thanks! Oct 25, 2021 at 19:56

# Python 3.8 (pre-release), 6867 65 bytes

lambda c:[(a,b,c)for a in range(1,c)if(b:=(c*c-a*a)**.5)==b//1>a]


Try it online!

-1 by observing that a and b are never equal in a Pythagorean triple. -2 thanks to G B, by squaring by self-multiplying.

# 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)}


Try it online!

• n=>{for(q=p=n;p=--p||--q;)p*p+q*q-n*n||print(p,q,n)}
– tsh
Oct 19, 2021 at 0:01

# Brachylog, 2018 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


# APL (Dyalog Classic), 38 bytes

{,∘⍵¨k[⍸(⍵*2)=+/¨2*⍨k←∪,{⍵[⍋⍵]}¨⍳⍵ ⍵]}


Try it online!

-10 thanks to @ovs!!!!

dfn, takes the hypotenuse on right

• Two quick golfs: {⍵,n} can be shortened to ,∘n (bind n as a left argument to ,. n,⍨ would work as well), which means you don't need the assignment to n. And you can inline the assignment to k: 38 bytes
– ovs
Oct 18, 2021 at 12:33
• @ovs thanks for the nice rearranging!! Oct 18, 2021 at 18:09

# 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


Try it online!

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.

# K (ngn/k), 28 bytes

{+x,+(x=%+/*/2#,+:)#+&~|\=x}


Try it online!

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.

# Jelly, 10 9 bytes

ŒcÆḊ=¥Ƈ;€


Try it online!

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²+²)=²ŒṪ;€


Try it online!

### 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


# 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

Try it Online!

• Welcome to Code Golf, and nice first answer! Make sure to check out our tips for golfing in APL to see if there are any ways that you can shorten this. Oct 26, 2021 at 17:07
• Thanks for the suggestion! I'll definitely look at that. Oct 26, 2021 at 17:11

# Vyxal, 18 17 bytes

²Ṅ'Ḣ₃;'∆²A;:[√⌊vJ


Try it Online!

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.

• L2= can be Ḣ₃ (see this tip) Oct 18, 2021 at 6:55

# JavaScript (V8), 57 bytes

n=>(g=i=>(j=(n*n-++i*i)**.5)>i&&g(i,j%1||print(i,j,n)))


Try it online!

A quite straightforward approach.

# APL+WIN, 42 Bytes

Prompts for hypotenuse:

(((c*2)=+/¨n*2)/n←(,m∘.<m)/,m∘.,m←⍳c),¨c←⎕


Try it online! Thanks to Dyalog Classic

# 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);}


Try it online!

# Gaia, 12 bytes

s¦e⁻+
┅r+¦↑⁈


Try it online!

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


# TI-Basic, 34 bytes

Prompt C
For(A,1,C/√(2
√(C²-A²
If not(fPart(Ans
Disp {A,Ans,C
End

• I don't know TI-Basic but should that be Disp {A,Ans,C by any chance?
– Neil
Oct 18, 2021 at 18:45
• @Neil yes, I forgot to change it Oct 18, 2021 at 20:08

# 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);}


Try it online!

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.

• 70 bytes but I'm afraid it's a bit too hackish ;-)
– jdt
Oct 21, 2021 at 14:06
• @upkajdt You can't pass in an array constructed outside the function as an extra parameter to return values. Also your shifts impose restrictions beyond built in types (int) that your answers can handle which is pushing things. Oct 21, 2021 at 15:35
• @yeah, I know. still had some fun trying anything to get the bytes down and the printf is still bothering me =)
– jdt
Oct 21, 2021 at 15:42
• @upkajdt That's always the issue with C for challenges requiring an unknown amount of solution data. Even your hack wouldn't create an array big enough for some inputs. Since that's unrelated to C built-in limitations that's frowned upon. But printf will happily pump out as much data as needed with having to resize buffers. Oct 21, 2021 at 16:33

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}]")} Try it online! # Raku, 45 bytes {grep *²+*²==*²,flat .&combinations(2)X$_}


Try it online!

• $_ 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 named combinations, 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 operator X. • flat flattens 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. • grep consumes 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. # 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.

Try it online!

# 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.

# Wolfram Language (Mathematica), 47 bytes

Cases[Range@#~Subsets~{2},x_/;x.x==#^2:>{x,#}]&


Try it online!

# Vyxal, 22 bytes

ɾ:vɾZƛ÷v";f2ẇ'²∑⁰²=;vJ


Try it Online!

What a horrible mess. I'm sure there's so many shorter ways of doing this...

# 05AB1E, 14 bytes

L2.ÆʒnOInQ}εIª


Try it online!

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ª


Try it online!

# 05AB1E, 14 bytes

nÅœ2ùʒÅ²P}tεIª


Try it online!

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ª


Try it online!

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

• You can get the second one to 14 as well by replacing In with t and Dâ with ã (Cartesian power with implicit b=2)
– ovs
Oct 18, 2021 at 8:16
• @ovs I am afraid that dosen't work, but nvm I have found another 14-byter on the second solution using combinations without replacement Oct 18, 2021 at 8:22
• @ovs my bad I did the wrong replacement Oct 18, 2021 at 9:33
• The In -> t works in your first 14-byter as well
– ovs
Oct 18, 2021 at 9:44
• As @ovs mentions above, your ʒnOtQ} works in your first program as well for -1. Here also a 12-byter by appending before filtering: L2.ÆIδªʒnαQ (or alternatively the nαQ can be nRÆ_). Oct 19, 2021 at 6:37

# 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.