33
\$\begingroup\$

Pythagoras had his leg blown up in the war. It had to be amputated, and though he nearly died, he pulled through and made a full recovery. Now, after a year of walking with crutches, he gets the privilege of getting a prosthetic leg! Thing is, though, there are several that fit, but which ones?

The Task

Given a positive integer as input that is the length of one leg of a Pythagorean triple, output all possibilities for the other leg. For example, the smallest Pythagorean triple is (3,4,5), which forms a triangle with two legs of length 3 and 4, and a hypotenuse of length 5.

Examples

Leg:5
12

Leg:28
21
45
96
195

Leg:101
5100

Leg:1001
168
468
660
2880
3432
4080
5460
6468
10200
38532
45540
71568
501000

The Rules

  • Input will be a single positive integer n.
  • Output may be in any order, with any delimiter, in any base (though this base must be consistent), and with optional opening and closing braces, and optional trailing whitespace. That is, 1 2 3, [1,2,3], and 1,11,111 all fit this output specification.
  • You may assume that n will never be larger than one fourth of the fourth root of your language's limit (without using libraries). In practice, you may assume the input will be less than either this or 10,000, whichever is less.

Pythagoras is waiting on you, so better write your code quick and short!

\$\endgroup\$
  • 18
    \$\begingroup\$ He's a really strange guy. He's willing to wait a couple thousand years for computers to be invented, but not a couple more nanoseconds to read a few extra hundred bytes. A very precise man, to say the least. \$\endgroup\$ – corsiKa Dec 7 '15 at 16:30

18 Answers 18

4
\$\begingroup\$

Pyth - 13 bytes

Brute forces all possible ones up till n^2+1.

f!%.a,TQ1S*QQ

Test Suite.

\$\endgroup\$
11
\$\begingroup\$

Jelly, 8 bytes

²R²+²Æ²O

This answer is non-competing, since it uses features that have been implemented after the challenge was posted. Try it online!

This approach does not use floating point math, so it will give the correct answer as long as the intervening lists can fit into memory.

Idea

If (a, b, c) is a Pythagorean triple, there are strictly positive integers k, m, n such that the set equality {a, b} = {km2 - kn2, 2kmn} holds.

In particular, this means that a < b2 and b < a2, so for input a we can simply check if a2 + b2 is a perfect square for each b in {1, … a2}.

Code

            Input: x

²           Compute x².
 R          Get get range 1 ... x².
  ²         Square each integer in that range.
   +²       Add x² to each resulting square.
     Ʋ     Check if the resulting sums are perfect squares.
       O    Get all indices of ones.
\$\endgroup\$
10
\$\begingroup\$

Julia, 35 bytes

n->filter(i->hypot(i,n)%1==0,1:n^2)

This is an anonymous function that accepts an integer and returns an array.

For each i from 1 to the input squared, we compute the hypotenuse using Julia's built-in hypot function, and determine whether the fractional portion is 0. If so, we keep it, otherwise it's excluded.

\$\endgroup\$
6
\$\begingroup\$

CJam, 17 bytes

{:A2#{Amh1%!},1>}

This is an anonymous function that pops an integer from the stack and leaves an array in return.

Try it online!

Idea

If (a, b, c) is a Pythagorean triple, there are strictly positive integers k, m, n such that the set equality {a, b} = {km2 - kn2, 2kmn} holds.

In particular, this means that a < b2 and b < a2, so for input a we can simply check if a2 + b2 is a perfect square for each b in {1, … a2}.

Code

:A               Save the input in A.
  2#             Square it.
    {      },    Filter; for each B in {0, ..., A**2}:
     Amh           Calculate the hypotenuse of (A, B).
        1%!        Apply logical NOT to its fractional part.
                 Keep B if ! pushed 1.
             1>  Discard the first kept B (0).  
\$\endgroup\$
4
\$\begingroup\$

JavaScript ES6, 60 62

Same as the other answers, checking from 1 to a*a-1

a=>[...Array(a*a).keys()].filter(b=>b&&!(Math.hypot(a,b)%1))

Thx to @Mwr247 the shortest way to build a range in ES6

2 bytes saved thx @ETHproductions

\$\endgroup\$
  • \$\begingroup\$ Awesome! I think you could save a few bytes with a built-in: a=>[...Array(a*a).keys()].filter(b=>b&&!(Math.hypot(a,b)%1)) \$\endgroup\$ – ETHproductions Dec 8 '15 at 17:05
  • \$\begingroup\$ @ETHproductions thx, I need to learn more about the new math builtins \$\endgroup\$ – edc65 Dec 8 '15 at 18:19
  • \$\begingroup\$ Conveniently they're also discussed on the page you already linked. (I would have made the hypot suggestion myself but I wasn't logged in at the time.) \$\endgroup\$ – Neil Dec 9 '15 at 0:51
3
\$\begingroup\$

C, 96 bytes

Alternately increment y (the other leg) and z (the hypotenuse) until their difference drops to 1. Output every exact match (c==0) you encounter on the way.

int x,y,z;main(int c,char**a){for(x=z=atoi(a[1]);++y<z;c=x*x+y*y-z*z,c?z+=c>0:printf("%d ",y));}

Call the compiled program with n as parameter; it will output a space-separated list of decimal numbers.

Obviously not the shortest; I may find comfort in having the fastest.

$ time ./pyth 9999
200 2020 13332 13668 16968 44440 45360 54540 55660 137532 164832 168168 413080 494900 504900 617120 1514832 1851468 4544540 5554440 16663332 49990000 
real    0m0.846s
user    0m0.800s
sys     0m0.000s
\$\endgroup\$
3
\$\begingroup\$

Wolfram Language (Mathematica), 40 bytes

b/.Solve[#^2+b^2==c^2,PositiveIntegers]&

I'm using an undocumented form of Solve: when the list of variables is omitted, then Solve defaults to solving for all symbols in the expression. We thus save 6 bytes over the more regular Solve[#^2+b^2==c^2,{b,c},PositiveIntegers].

PositiveIntegers is new in version 12 of Mathematica and thus not available in TIO. In desktop Mathematica, we get

F = b/.Solve[#^2+b^2==c^2,PositiveIntegers]& ;

F[5]
(*    {12}    *)

F[28]
(*    {21, 45, 96, 195}    *)

F[101]
(*    {5100}    *)

F[1001]
(*    {168, 468, 660, 2880, 3432, 4080, 5460, 6468, 10200, 38532, 45540, 71568, 501000}    *)
\$\endgroup\$
2
\$\begingroup\$

Python 2, 53 bytes

lambda n:[i for i in range(1,n*n)if abs(i+n*1j)%1==0]

A straightforward solution using complex abs to compute the length of the hypotenuse. It's safe to use n*n as an upper bound for the other leg because (n*n)^2 + n^2 < (n*n+1)^2. I tried using recursion instead but didn't get anything shorter.

\$\endgroup\$
2
\$\begingroup\$

Seriously, 20 bytes

,;╗ªDR;`╜@ÇA1@%Y`M@░

Same strategy as xnor's Python answer: check i in range(1,n*n) for values where abs(i+nj) % 1 == 0, and output the list. Try it online

Explanation:

,;╗    get input and save a copy in register 0
ªDR;   push two copies of range(1,n*n)
`╜@ÇA1@%Y`M    map the function across one of the ranges:
    ╜@ÇA         compute abs(i+nj)
    1@%Y         push 1 if result % 1 is 0, else 0
M@░    swap the two lists, take values in the original range where the corresponding values in the second range are truthy
\$\endgroup\$
2
\$\begingroup\$

PARI/GP, 36 bytes

x->[y|y<-[1..x^2],issquare(x^2+y^2)]
\$\endgroup\$
2
\$\begingroup\$

APL(NARS), 373 chars, 746 bytes

C←{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}⋄P←{1≥k←≢w←,⍵:⊂w⋄↑,/{w[⍵],¨P w[a∼⍵]}¨a←⍳k}⋄d←{∪×/¨{k←≢b←1,π⍵⋄∪{b[⍵]}¨↑∪/101 1‼k k}⍵}⋄t←{(-/k),(×/2,⍵),+/k←⍵*2}⋄b←{⍬≡a←3 C d w←⍵:(⊂1,⍵,1)⋄(⊂1,⍵,1),a/⍨{⍵[2]>⍵[3]}¨a←↑∪/P¨,a/⍨{w=×/⍵}¨a}⋄u←{(↑⍵),2÷⍨(+/a),-/a←1↓⍵}⋄t1←{(↑¨⍵)×t¨1↓¨⍵}⋄f1←{0=2∣⍵:↑¨t1 b⍵÷2⋄{2⊃⍵}¨t1 u¨b⍵}⋄f←{m←⎕ct⋄⎕ct←0⋄r←f1⍵⋄⎕ct←m⋄r}

comment:

C: ⍺ combination in ⍵ list
P: permutations  in ⍵ list
d: divisors of ⍵ unsigned
t: Pythagorian triple from ⍵ list 2 unsigned
b: if argument ⍵ is one unsigned it would return the list of (k,i,j) where 
   k,i,j are all divisors of ⍵, and ⍵=k×i×j and i>j
u: from one triple (k,i,j) return (k,(i+j)/2,(i-j)/2)
t1: apply (k,i,j) to t in the way  k×t i,j 
f: the function of this exercise

The idea would be factor the input for to know the possible m,n that generate using t all Pythagorian triple that has the input as leg. Test:

  f 18298292829831839x
167413760243137645229428509060960 15219432749376149566311682641900 99808869980900940 
  1383584795397831778755607512840 
  f 5
12
  f 28
195 96 21 45 
  f 101
5100
  f 1001
501000 6468 38532 2880 468 660 168 5460 45540 4080 71568 3432 10200 
  ≢f 1001
13
  f 1663481166348349x
1383584795397831778755607512900 
  f 198820182831x
19764732550476133587280 346749693868002343608 5664631173992 6083327962596530720 613900915408 115583231289334114460 
  18249983887789596492 1883559626820 1040249081604007030900 54749951663368790920 6588244183492044529092 
  265093577108 2196081394497348176360 
\$\endgroup\$
2
\$\begingroup\$

APL (Dyalog Extended), 15 14 bytesSBCS

Anonymous tacit prefix function.

(⍸⊢(+∊⊢)⍳×⍳)×⍨

Try it online!

×⍨ square (lit. multiplication selfie of) the argument

() apply the following anonymous tacit function:

ɩntegers 1 through the argument

 multiply by ɩntegers 1 through the argument (i.e. square)

⊢() apply the following anonymous tacit function with the argument as left argument:

  + is the sum

   a member of

   it?

ɩndices of truths

\$\endgroup\$
1
\$\begingroup\$

Perl 5, 43 bytes

$i=<>;{sqrt(++$_**2+$i**2)!~/\./&&say;redo}

If you want the script to terminate, we can inspect other legs up to n² only, as explained by xnor, so we have 48 bytes:

map{sqrt(++$_**2+$i**2)!~/\./&&say}1..($i=<>)**2
\$\endgroup\$
1
\$\begingroup\$

Japt, 16 bytes

1oU² f@!(MhXU %1

Try it online!

How it works

        // Implicit: U = input integer
1oU²    // Generate a range of integers from 1 to U squared.
f@!(    // Keep only items X that return falsily to:
MhXU %1 //  Math.hypot(X,U) % 1.
        // This keeps only the items where sqrt(X*X+U*U) = 0.
        // Implicit: output last expression
\$\endgroup\$
1
\$\begingroup\$

Stax, 8 bytes

î←■↑»⌐╚â

Run and debug it

In pseudo-code:

(1..n²).filter(d -> is-square(n² + d²))
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 10 bytes

nDLn+Ųƶ0K

Try it online or verify all test cases.

nDLʒnIn+Ų

Try it online or verify all test cases.

Explanation:

n           # Take the square of the (implicit) input-integer
 D          # Duplicate it
  L         # Create a list in the range [1, input^2]
   n        # Square each value in this list
    +       # Add the input^2 we duplicated to each
     Ų     # Check for each of these if it's a square (1 if truthy; 0 if falsey)
       ƶ    # Multiply each value by its 1-based index
        0K  # Remove all 0s from the list
            # (after which the result is output implicitly)

nDL         # Same as above
   ʒ        # Filter this list by:
    n       #  Get the square of the current number
     In+    #  Add the squared input to it
        Ų  #  And check if it's a square
            # (after the filter, implicitly output the result)
\$\endgroup\$
1
\$\begingroup\$

MathGolf, 9 bytes

²╒gƲk²+°

Try it online!

Couldn't find a nice way to remove any of the ²s, which take up 3/9 bytes. Otherwise it is quite straight-forward

Explanation

²           square input
 ╒          range(1,n+1)
  gÆ        filter list using next 5 operators
    ²       square list element
     k²     push input squared
       +    pop a, b : push(a+b)
        °   is perfect square
\$\endgroup\$
1
\$\begingroup\$

Java 8, 72 bytes

n->{for(int i=0;++i<n*n;)if(Math.hypot(i,n)%1==0)System.out.println(i);}

Try it online.

Explanation:

n->{                           // Method with integer as parameter and no return-type
  for(int i=0;++i<n*n;)        //  Loop `i` in the range (0, n²)):
    if(Math.hypot(i,n)         //   If sqrt(i² + n²)
       %1==0)                  //   has no decimal digits after the comma (so is an integer)
      System.out.println(i);}  //    Output `i` with trailing newline
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.