36
\$\begingroup\$

A common visual explanation of the Pythagorean theorem is as such:

3 boxes

The squares are meant to represent the side length's squared, and the areas of a + b = c, just like the Pythagorean theorem says.

This part is what you have to show.

Your task

  • You will get two integers as input, meant to represent sides a and b of a right triangle (ex. 3, 4).
  • You will then make squares out of the lengths a, b, and c out of the # character. For example here is 3:
###
###
###
  • You will then format these into a math equation that explains the particular Pythagorean triplet:
             #####
      ####   #####
###   ####   #####
###   ####   #####
### + #### = #####
  • Notice how the = and + signs have spaces on both sides and how everything is on the bottom.
  • You will never get values for a and b that make c non-integral.
  • This is so shortest code in bytes wins!

Test Cases

(more coming once I have time, these are really hard to make by hand)

3, 4
             #####
      ####   #####
###   ####   #####
###   ####   #####
### + #### = #####

6, 8
                    ##########
                    ##########
         ########   ##########
         ########   ##########
######   ########   ##########
######   ########   ##########
######   ########   ##########
######   ########   ##########
######   ########   ##########
###### + ######## = ##########

4, 3
             #####
####         #####
####   ###   #####
####   ###   #####
#### + ### = #####

5, 12
                       #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
        ############   #############
#####   ############   #############
#####   ############   #############
#####   ############   #############
#####   ############   #############
##### + ############ = #############
\$\endgroup\$
  • 3
    \$\begingroup\$ @bmarks "You will never get values for a and b that make c non-integral." \$\endgroup\$ – Maltysen Aug 31 '15 at 21:15
  • 2
    \$\begingroup\$ @RetoKoradi well the areas of the squares a+b=c \$\endgroup\$ – Maltysen Aug 31 '15 at 22:58
  • 1
    \$\begingroup\$ If a, b and c are defined as the areas of the squares, then the examples are incorrect. \$\endgroup\$ – Reto Koradi Aug 31 '15 at 23:01
  • 2
    \$\begingroup\$ You should add another nice test case, like 5 + 12 = 13. \$\endgroup\$ – mbomb007 Sep 1 '15 at 0:33
  • 7
    \$\begingroup\$ Note: this is not "a visual explanation of the Pythagorean theorem". This is the Pythagorean theorem. It was originally formulated exactly this way: geometrically. They didn't even know about square roots, even more interesting, Pythagoras himself didn't believe in the existence of irrational numbers. This means Pythagoras thought that sqrt(2) can be exactly represented by the division of two finite integers. The original theorem is what we now call the "visual representation" \$\endgroup\$ – vsz Sep 1 '15 at 21:07

18 Answers 18

17
\$\begingroup\$

Pyth, 35 32 31 30 bytes

j_.ts.i.imm*d\#d+Qs.aQ"+="mk4d

Try it online.

\$\endgroup\$
  • \$\begingroup\$ You can save a byte by using .i to add the blank lines instead: j_.ts.i.imm*d\#d+Qs.aQ"+="mk4d \$\endgroup\$ – isaacg Sep 1 '15 at 7:44
12
\$\begingroup\$

CJam, 49 bytes

" +   = "S/3/[q~_2$mh:H]_'#f*:a.*.\:+SH*f.e|zW%N*

Try it online in the CJam interpreter.

How it works

" +   = "S/3/ e# Split at spaces, the into chunks of length 3.
              e# This pushes [["" "+" ""] ["" "=" ""]].
[             e#
  q~          e# Read and interpret all input from STDIN.
  _2$         e# Copy both integers.
  mh          e# Calculate the hypotenuse of the triangle with those catheti.
  :H          e# Save the result in H.
]             e# Collect catheti and hypotenuse in an array.
_'#f*         e# Copy and replace each length with a string of that many hashes.
:a            e# Wrap each string in an array.
.*            e# Vectorized repetition. Turns strings into square arrays.
.\            e# Interleave with the string of operators.
:+            e# Concatenate to form an array of strings.
SH*           e# Push a string of spaces of length H.
f.e|          e# Mapped vectorized logical OR; pads all strings with spaces to
              e# length H.
zW%           e# Zip and reverse; rotates the array.
N*            e# Join the strings, separating by linefeeds.
\$\endgroup\$
11
\$\begingroup\$

Python 2, 134 100 bytes

a,b=input()
i=c=int(abs(a+b*1j))
while i:print"# "[i>a]*a," +"[i<2],"# "[i>b]*b," ="[i<2],"#"*c;i-=1

Try it online.

The program takes input as comma-separated integers, calculates the hypotenuse using Python's built-in complex numbers, then loops down from that value calculating and printing each line as it goes. The main golfing trick is using string indexing in place of conditionals to select #/+/= vs space.

Edit: The first version was a victim of some serious over-engineering--this one is both simpler and much shorter.

\$\endgroup\$
  • \$\begingroup\$ I just got the same thing, having taken a while to realize it's shorter to just repeat "# "[i>a]*a instead of doing it for each variable. \$\endgroup\$ – xnor Sep 1 '15 at 1:47
11
\$\begingroup\$

Julia, 121 114 112 bytes

f(a,b)=for i=1:(c=isqrt(a^2+b^2)) g(x,t)=(i>c-x?"#":" ")^x*(i<c?"  ":t)" ";println(g(a," +")g(b," =")g(c,""))end

Ungolfed:

function f(a,b)
    # Compute the hypotenuse length
    c = isqrt(a^2 + b^2)

    # Write the lines in a loop
    for i = 1:c
        # Make a function for constructing the blocks
        g(x,t) = (i <= c - x ? " " : "#")^x * (i < c ? "  " : t) " "

        println(g(a," +") g(b," =") g(c,""))
    end
end

Fixed issue and saved 2 bytes thanks to Glen O.

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

JavaScript ES6, 155 134 140 129 bytes

(n,m)=>eval("for(o='',q=(b,s)=>' #'[z<b|0].repeat(b)+(z?'   ':s),z=i=Math.hypot(n,m);z--;)o+=q(n,' + ')+q(m,' = ')+q(i,'')+`\n`")

I've rewritten this with for. Lots of golfing still...

If something isn't working, let me know. I'll fix it in the morning.

Tested on Safari Nightly

Ungolfed:

(n,m)=>
   Array(
     z=Math.hypot(n,m)
   ).fill()
   .map((l,i)=>
      (q=(j,s)=>
        (z-i<=j?'#':' ')
        .repeat(j)+
         (z-i-1?' ':s)
      )
      (n,`+`)+
      q(m,`=`)+
      q(z,'')
   ).join`
   `

Explanation:

(Not updated) but still accurate enough.

(n,m)=> // Function with two arguments n,m
   Array( // Create array of length...
    z=Math.hypot(n,m) // Get sqrt(n^2+m^2) and store in z
   ).fill() // Fill array so we can loop
   .map((l,i) => // Loop z times, take l, and i (index)
     (q=j=>( // Create function q with argument j
      z-i<=j? // If z-i is less than or equal to j...
        '#' // Use '#'
      : // OR
        ' ' // Use space
      ).repeat(j) // Repeat the character j times
     )(n) // Run with n
   + // Add to string
   ` ${ // Space
      (b=z-i-1)? // If this isn't the last line...
       ' ' // Return ' '
      : // Otherwise
       '+' // Plus
    } ${ // Space
      q(m) // run function q with arg m
    } ${ // Space
      b? // If b
       ' ' // Return space
      : // Otherwise
        '=' // '='
    }` + // Add to...
    '#'.repeat(z) // Repeat hashtag, z times
  ).join` // Join the new array with new lines
  `

DEMO

ES5 version Input must be valid sets of numbers:

function _taggedTemplateLiteral(e,t){return Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var _templateObject=_taggedTemplateLiteral(["\n"],["\n"]),t=function(e,t){return Array(z=Math.sqrt(e*e+t*t)).fill().map(function(r,n){return(q=function(e,t){return(z-n<=e?"#":" ").repeat(e)+(z-n-1?" ":t)})(e,"+")+q(t,"=")+q(z,"")}).join(_templateObject)};
// Demo
document.getElementById('go').onclick=function(){
  document.getElementById('output').innerHTML = t(+document.getElementById('input').value,
                                                 +document.getElementById('input2').value)
};
<div style="padding-left:5px;padding-right:5px;"><h2 style="font-family:sans-serif">Visually Explaining the Pythagorean Theorem</h2><div><div  style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><input placeholder="Number 1" style="resize:none;border:1px solid #DDD;" id="input"><input placeholder="Number 2" style="resize:none;border:1px solid #DDD;" id="input2"><button id='go'>Run!</button></div><br><div style="background-color:#EFEFEF;border-radius:4px;padding:10px;"><span style="font-family:sans-serif;">Output:</span><br><pre id="output" style="background-color:#DEDEDE;padding:1em;border-radius:2px;overflow-x:auto;"></pre></div></div></div>

\$\endgroup\$
  • 2
    \$\begingroup\$ +1, but there's a small issue as the OP says: "Notice how the = and + signs have spaces on both sides and how everything is on the bottom." \$\endgroup\$ – Léo Lam Sep 1 '15 at 7:12
  • 1
    \$\begingroup\$ The snippet isn't working on Firefox 40.0.3 (Windows 7x64 SP1). \$\endgroup\$ – Ismael Miguel Sep 1 '15 at 10:19
  • 1
    \$\begingroup\$ Snippet not working in Chromium 44 Linux x64 \$\endgroup\$ – Nenotlep Sep 1 '15 at 11:08
  • 2
    \$\begingroup\$ @IsmaelMiguel Those latter cases aren't necessary to handle correctly, though: "You will never get values for a and b that make c non-integral." \$\endgroup\$ – DLosc Sep 1 '15 at 18:26
  • 2
    \$\begingroup\$ +1 nice use of eval. Hint: (z<b?'#':' ') -> ' #'[z<b|0] \$\endgroup\$ – edc65 Sep 2 '15 at 9:41
7
\$\begingroup\$

Pyth, 51 49 bytes

AQJs.aQLj*b]*b\#;j_MCm_.[d\ Jcj[yJb\=byHb\+byG))b

Expects input in the form [3,4].

Try it here

AQ - assigns input to G, H

Js.a,GH - calculates hypotenuse as J

Lj*b]*b\#; - defines y(b) as making a square of size b (elsewhere in the code, b means newline)

j_MCm_.[d\ Jcj[yJb\=byHb\+byG))b - Creates the squares, pads with spaces, and transposes

Saved two bytes thanks to Maltysen.

\$\endgroup\$
  • \$\begingroup\$ I don't know exactly what your code does, but I'm pretty sure it can benefit from .interlace instead of all those lists. \$\endgroup\$ – Maltysen Sep 1 '15 at 1:11
  • \$\begingroup\$ @Maltysen To your last comment, actually I can't, because the first appearance of J is inside a lambda, which gets evaluated after J is first used. \$\endgroup\$ – Ypnypn Sep 1 '15 at 1:16
  • \$\begingroup\$ ah, didn't see that. Another thing: *] can be replaced with m \$\endgroup\$ – Maltysen Sep 1 '15 at 1:18
3
\$\begingroup\$

Ruby, 134

->a,b{c=((a**2+b**2)**0.5).round
c.times{|i|
d=i<c-1?'  ':'+='
puts (c-i>a ?' ':?#)*a+" #{d[0]}  #{(c-i>b ?' ':?#)*b} #{d[1]} "+?#*c}}

simple line by line approach.

Below in test program, with symbol changed to @ to help avoid confusting with the syntax #{....} ("string interpolation") used to insert expressions into a string. Each input should be given on a different line.

f=->a,b{c=((a**2+b**2)**0.5).round
c.times{|i|
d=i<c-1?'  ':'+='
puts (c-i>a ?' ':?@)*a+" #{d[0]}  #{(c-i>b ?' ':?@)*b} #{d[1]} "+?@*c}}

A=gets.to_i
B=gets.to_i
f.call(A,B)
\$\endgroup\$
  • \$\begingroup\$ I don't know Ruby, but I'm guessing this can get shorter, since Ruby solutions often beat Python solutions (in my anecdotal experience). For starters, a*a+b*b should cut two bytes from the computation of c. \$\endgroup\$ – DLosc Sep 1 '15 at 23:54
3
\$\begingroup\$

C, 176 bytes

C is not going to win this, but the fun is worth it.

#define A(x,y)for(j=x;j--;)putchar("# "[i+1>x]);printf(i?"   ":" "#y" ");
i;j;main(a,b,c){for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c;c++);for(i=c;i--;puts("")){A(a,+)A(b,=)A(c,)}}

Pretty printed:

#define A(x,y)for(j=x;j--;)putchar("# "[i+1>x]);printf(i?"   ":" "#y" ");
i;j;
main(a,b,c)
{
    for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c;c++);
    for(i=c;i--;puts(""))
    {
        A(a,+)
        A(b,=)
        A(c,)
    }
}

gcc enables us to pass third parameter to main (an array of environment variables), so we take advantage of it to use it for our purpose.

The

for(c=scanf("%d %d",&a,&b);a*a+b*b>c*c++;);

would be equivalent to

scanf("%d %d",&a,&b);
for(c=2;a*a+b*b>c*c++;);

because scanf returns the number of successfully scaned parameters.

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

PHP, 178 170 168 bytes

Input is GET parameters x and y. Unfortunately I can't seem to golf those repeating strings.

<?php for(@$i=$z=hypot($x=$_GET[x],$y=$_GET[y]),@$s=str_repeat;$i;$i--)@print$s($i<=$x?~Ü:~ß,$x).(($l=$i==1)?~ßÔß:~ßßß).$s($i<=$y?~Ü:~ß,$y).($l?~ßÂß:~ßßß).$s(~Ü,$z).~õ;
  • Saved 8 bytes by inverting all my strings and dropping the quotes.
  • Saved 2 bytes by replacing the condition $i>0 with $i

Not sure why PHP doesn't like @echo so I had to sacrifice 1 byte with @print.

In case SE screws up the encoding, this is meant to be encoded in Windows-1252 (not UTF8).

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

APL (Dyalog Extended), 33 29 bytesSBCS

-3 due to my extensions of Dyalog APL.

Anonymous prefix lambda:

{⊖⍕,' +=',⍪{⍵ ⍵⍴⍕#}¨⍵,√+/⍵*2}

Try it online!

{} "dfn"; is the argument (side lengths)

⍵*2 square

+/ sum

 square-root

⍵, prepend argument

{ apply the following anonymous lambda to each

  # root namespace

   format as text

  ⍵ ⍵⍴ use argument twice to reshape into matrix with those dimensions.

 make into column

' ++=', prepend these three characters to the three rows

, ravel (combine rows into list)

 format as text

 flip upside-down

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

CJam, 78 bytes

q~_2f#~+mQ+ee_2=~e>f{\~@1$-S*\'#*+_'#e=\a*_0=,S*@"+= "=1$,(S*\+1$a\a@a+++~}zN*

It first computes the hypotenuse (H), then, for each side (S), it builds an array of S lines made of: H-S spaces + S dashes. Finally, it transposes the matrix.

Demo

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

Lua5.2, 257 241 227 222 bytes

r=io.read
a=r"*n"b=r"*n"c=math.sqrt(a^2+b^2)d=a+b
w=io.write
for i=1,c do
for j=0,d+c+5 do
w((j>d+5 or(i>c-b and j>a+2 and j<d+3)or(i>c-a and j<a))and"#"or(i==c and(j==a+1 and"+"or(j==d+4 and"="or" "))or" "))end
w"\n"end
  • Edit1: Simplified reading
  • Edit2: Removed more whitespaces
  • Edit3: aliases abstraction of io functions inspired by another answer
\$\endgroup\$
1
\$\begingroup\$

Charcoal, 24 bytes

⊞θ₂ΣXθ²F =+«←←←ι←G↑←↓⊟θ#

Try it online! Link is to verbose version of code. Takes input as an array of two elements. Explanation:

⊞θ₂ΣXθ²

Append the hypotenuse to the inputs.

F =+«

Loop over the characters that appear to the right of each square in reverse order.

←←←ι←

Print that character leftwards with spacing.

G↑←↓⊟θ#

Pop the last number from the array and print a square of #s of that size.

\$\endgroup\$
  • 1
    \$\begingroup\$ @KevinCruijssen Whoa, what an oversight! Should be fixed now. \$\endgroup\$ – Neil Jan 14 at 16:42
1
\$\begingroup\$

PowerShell, 139 137 135 bytes

-2 thanks to ASCII-only
-2 thanks to Mazzy

param($a,$b)($c=[math]::sqrt($a*$a+$b*$b))..1|%{(($m=" ","#")[$_-le$a]*$a)," +"[$_-eq1],($m[$_-le$b]*$b)," ="[$_-eq1],("#"*$c)-join" "}

Try it online!

Calculating $c hurt and there's probably a better way to conditionally swap between # and . Builds a list of chunks and joins them together while conditionally adding the signs.

\$\endgroup\$
  • 1
    \$\begingroup\$ there is a redundant brackets in $m=(" ","#"): Try it online! \$\endgroup\$ – mazzy Jan 16 at 6:17
  • \$\begingroup\$ @mazzy Ha ha, whoops \$\endgroup\$ – Veskah Jan 16 at 21:01
0
\$\begingroup\$

Japt, 28 bytes

Takes input as an array of integers.

pUx²¬)ËÆDç'#
í"+="¬ûR3)c ·z3

Try it

                    :Implicit input of array U=[a,b]
pUx²¬)ËÆDç'#
p                   :Push
 U ²                :  Square each element in U
  x                 :  Reduce by addition
    ¬               :  Square root
     )              :End push
      Ë             :Map each D
       Æ            :  Map the range [0,D)
        Dç'#        :    Repeat "#" D times
í"+="¬ûR3)c ·z3
í                   :Interleave
 "+="¬              :  Split the string "+=" to an array of characters
      û             :  Centre pad each
       R3           :    With newlines to length 3
         )          :End interleave
          c         :Flatten
            ·       :Join with newlines
             z3     :Rotate clockwise 270 degrees
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 38 bytes

nOtª©Å10ζíε„ #yè®Rׄ= NĀèð.øý}»R„=+`.;

Takes the input as a list of two numbers (i.e. [3,4]).

Try it online or verify all test cases.

Explanation:

n             # Take the square of each value in the (implicit) input-list
              #  i.e. [3,4] → [9,16]
 O            # Take the same of that list
              #  i.e. [9,16] → 25
  t           # Take the square-root of that sum
              #  i.e. 25 → 5.0
   ª          # Append it to the (implicit) input-list
              #  i.e. [3,4] and 5.0 → [3,4,5.0]
    ©         # Store it in the register (without popping)
Å1            # Change each value to an inner list of that amount of 1s
              #  i.e. [3,4,5.0] → [[1,1,1],[1,1,1,1],[1,1,1,1,1]]
  0ζ          # Zip/transpose; swapping rows/columns, with "0" as filler
              #  i.e. [[1,1,1],[1,1,1,1],[1,1,1,1,1]]
              #   → [[1,1,1],[1,1,1],[1,1,1],["0",1,1],["0","0",1]]
    í         # Reverse each inner list
              #  i.e. [[1,1,1],[1,1,1],[1,1,1],["0",1,1],["0","0",1]]
              #   → [[1,1,1],[1,1,1],[1,1,1],[1,1,"0"],[1,"0","0"]]
ε         }   # Map the inner lists to:
 „ #          #  Push string " #"
    yè        #  Index each inner list value into this string
              #   i.e. " #" and [1,1,"0"] → ["#","#"," "]
      ®R      #  Push the list from the register
        ×     #  Repeat the character that many times
              #   i.e. ["#","#"," "] and [5.0,4,3] → ["#####","####","   "]
 „=           #  Push string "= "
   NĀ         #  Push the map-index trutified (0 remains 0; everything else becomes 1)
              #   i.e. 0 → 0
              #   i.e. 3 → 1
     è        #  Use it to index into the string
              #   i.e. "= " and 0 → "="
              #   i.e. "= " and 1 → " "
      ð.ø     #  Surround it with spaces
              #   i.e. "=" → " = "
              #   i.e. " " → "   "
         ý    #  Join the map-list together with this string as delimiter
              #   i.e. ["#####","####","   "] and "   " → "#####   ####      "
»             # After the map, join everything by newlines
              #  i.e. ["##### = #### = ###","#####   ####   ###","#####   ####   ###","#####   ####      ","#####             "]
              #   → "##### = #### = ###\n#####   ####   ###\n#####   ####   ###\n#####   ####      \n#####             "
 R            # Reverse the string
              #  i.e. "##### = #### = ###\n#####   ####   ###\n#####   ####   ###\n#####   ####      \n#####             "
              #   → "             #####\n      ####   #####\n###   ####   #####\n###   ####   #####\n### = #### = #####"
  „=+`.;      # And replace the first "=" with "+"
              #  i.e. "             #####\n      ####   #####\n###   ####   #####\n###   ####   #####\n### = #### = #####"
              #   → "             #####\n      ####   #####\n###   ####   #####\n###   ####   #####\n### + #### = #####"
              # (and output the result implicitly)
\$\endgroup\$
  • \$\begingroup\$ DnOt©)˜ε'#×y.Dðy×®y-.D)R}ø» was my attempt until I noticed the + and =. \$\endgroup\$ – Magic Octopus Urn Jan 16 at 18:48
  • \$\begingroup\$ @MagicOctopusUrn Yeah, those three spaces and + and = are indeed responsible for the most part of the code. Btw, you can golf 2 bytes in your approach by replacing DnOt©)˜ with nOt©ª, as I did in my current answer. :) I like your use of .D, though. \$\endgroup\$ – Kevin Cruijssen Jan 17 at 9:00
0
\$\begingroup\$

Perl 6, 99 bytes

{$!=sqrt $^a²+$^b²;flip map({map {[' ','#'][$^d>$_]x$d,' =+ '.comb[!$_*++$ ]},$!,$b,$a},^$!)X"
"}

Try it online!

Anonymous code block that takes two numbers and returns the full string with a leading newline and three leading spaces and one trailing on each line.

If we can use other characters instead of #, then I can save a byte by replacing '#' with \*.

\$\endgroup\$
0
\$\begingroup\$

C# (.NET Core), 221, 194 bytes

This feels way too long. This version just loops to construct the string.

EDIT: Ascii-Only with a nice -27 byte golf using the string constructor for serial char additions! Also, ty for pointing out I was using Math.Sqrt not System.Math.Sqrt. This has been adjusted!

(a,b)=>{int c=(int)System.Math.Sqrt(a*a+b*b),j=c;var s="";while(j>0)s+=new string(j>a?' ':'#',a)+(j>1?"   ":" + ")+new string(j>b?' ':'#',b)+(j-->1?"   ":" = ")+new string('#',c)+"\n";return s;}

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ remember the ending semicolon isn't needed, and also System.Math not Math if you're not using interactive \$\endgroup\$ – ASCII-only Jan 16 at 3:08
  • \$\begingroup\$ 211? \$\endgroup\$ – ASCII-only Jan 16 at 3:13
  • 1
    \$\begingroup\$ 187? \$\endgroup\$ – ASCII-only Jan 16 at 3:22
  • \$\begingroup\$ One thing, I'd remove all using directives to make sure I didn't make a mistake \$\endgroup\$ – ASCII-only Jan 17 at 0:14
  • 1
    \$\begingroup\$ Oh and since you no longer have the ternary version I don't think you should mention it anymore \$\endgroup\$ – ASCII-only Jan 17 at 0:21

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.