# Shortest method to implement the Pythagorean Theorem

Who doesn't love the Pythagorean theorem $$\a^2+b^2=c^2\$$? Write the shortest method you can in any language that takes in value a and b and prints out The hypotenuse of this right triangle is c. Keep c to only three decimal places.

• Shortest in characters or bytes? :) Commented Feb 5, 2014 at 20:53
• shortest in characters Commented Feb 5, 2014 at 20:55
• The code-golf tag explicitly says "Code-golf is a competition to solve a particular problem in the fewest bytes of source code." See Scoring code golf (bytes vs. characters). Commented Feb 6, 2014 at 12:47

## APL (54)

'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2


Test:

      'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2
⎕:
9 10
The hypotenuse of this right triangle is 13.454


Explanation:

• ⎕*2: raise the values in the input to the second power
• +/: take the sum
• .5*⍨: raise the result to the 0.5th power
• 3⍕: round to 3 decimal places
• This is about unbeatable Commented Feb 5, 2014 at 19:16
• @Cruncher: I tried to encode the string but couldn't get the decoding routine small enough. Commented Feb 5, 2014 at 19:37
• By the pigeon hole principle, I think you'd have a really hard time (maybe impossible. It has to be impossible for at least some strings) trying to compress the string. Maybe if the string had some logical pattern, but that doesn't appear to be the case. I'm interested to see the attempts you've had so far though Commented Feb 5, 2014 at 20:38
• Correct the spelling of "hypotenuse" to save a character. Commented Feb 5, 2014 at 20:45
• @Cruncher: Actually, I beat it in Sclipting... Commented Feb 6, 2014 at 15:04

# TI-BASIC, 765553 52 bytes

Input :Disp "THE HYPOTENUSE OF THIS RIGHT TRIANGLE IS
Fix 3:R▶Pr(X,Y


No, a closing parentheses is not required. Also, less bytes than that APL answer :)

• Could be R▶Pr(A,B. Commented Jun 8, 2015 at 1:57
• 2 years to implement a suggestion, lol. Commented Sep 13, 2017 at 18:51
• Destined for greatness, I guess. And I just shaved off two more bytes to beat APL! Commented Sep 13, 2017 at 19:38
• -1 byte: Fix 3:R►Pr(X,Y Commented Oct 21, 2017 at 19:35
• Using Input to ask for X and Y is kind of hilarious. If we allow that, should we also allow setting PolarGC before Input, so that the length of the hypotenuse is given by the one-byte R? Admittedly, with PolarGC the values of X and Y are no longer displayed when we move the cursor around, but they're still stored to the appropriate variables. (Which we would then never use, but it's the thought that counts.) Commented Oct 23, 2017 at 3:12

# Python 2.7 - 76 Characters

print'The hypotenuse of this right triangle is %.3f'%abs(input()+1j*input())


Explanation

$$|a+bi| = \sqrt{a^2 + b^2} = c \\ \implies a^2 + b^2 = c^2$$

PJ on hypotenuse

Teacher: "Can you tell me, what is hypotenuse?"

LJ: "Hypotenuse, an easy question. If there's a high profile party last night, and you read it in the news paper, its called High Party News"

# Sclipting, 46 characters

글坼各갠方終加감半方갾밈乘增貶껠矽녆둥긆둹댆뭴뉖멵댶넠닶눠덆둩댲걲늖덨덂건댦땡닦덬뉒걩댲밀⓶


Expects the input as two numbers (can be fractional!) separated by a space.

This is shorter than APL, despite having to use a few inconvenient tricks.

## Explanation

글坼 | split at space

갠方 | to the power of two

감半方 | to the power of one half
갾밈乘 | multiply by 1000

껠矽 | insert '.' at 4th-last character position
녆둥긆둹댆뭴뉖멵댶넠닶눠덆둩댲걲늖덨덂건댦땡닦덬뉒걩댲밀⓶ | "The hypotenuse..."

• doesn't unicode make this like 92 bytes? Commented Feb 6, 2014 at 17:43
• @Cruncher I asked yesterday up in the question comments, what counts is character count, not byte count. Commented Feb 6, 2014 at 21:55

# dc 54

Tangents the score of the APL answer!

2^r2^+3kv[The hypotenuse of this right triangle is ]Pp


Test:

$dc 3 4 2^r2^+3kv[The hypotenuse of this right triangle is ]Pp The hypotenuse of this right triangle is 5.000  • doesn' really work for me. dc -e '2^r2^+3kv[The hypotenuse of this right triangle is ]Pp' doesn't wait for any input, prints "dc: stack empty" 3 times and then "The hypotenuse of this right triangle is 2.000". Commented Feb 6, 2014 at 13:19 • @Tomas it's sort of a a function; you need to put the parameters on the stack first, like I show in the test, or if you want to invoke your way, it would be dc -e '3 4 2^r2^+3kv[... where 3 and 4 are the parameters. Commented Feb 6, 2014 at 14:03 ## C, 77 or 99 77 characters if input can just be the function arguments: f(a,b){printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}  99 if input must be read from stdin: a,b;f(){scanf("%d %d",&a,&b);printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}  A big thanks to @Yimin Rong! • There is a hypot(a,b) which will save you three characters. – user15259 Commented Feb 5, 2014 at 18:03 • That function not compile whatever compile I use gcc tcc clang in tio...perhaps lack one #include header and in the title the precise version of the compiler – user58988 Commented Oct 23, 2017 at 10:20 Powershell Just to see if i could... echo "The hypotenuse of this right triangle is " ([math]::round([math]::sqrt(([math]::pow(([double](Read-Host -p "A")),2) + [math]::pow(([double](Read-Host -p "B")),2))),3))  • Nice work. Looks like you did this while I was busy with my own solution, which beats this by about 62 characters. For future reference, Code Golf answers are expected to be "golfed" and have their "score" included. "Golfing" means that you should make every effort to reduce the character length by using short-hand aliases, syntax tricks, and other means of stretching the language's rules. You should also remove unnecessary whitespace where possible (there's at least three spaces that can be removed from your solution). The "score", in this case, is your character count - currently 173. – Iszi Commented Feb 6, 2014 at 8:23 • I suggest reading the code golf tag wiki, various portions of the Help Center, and the Golfing Tips for PowerShell thread to get a better feel for how to write a competitive answer to code golf challenges here. – Iszi Commented Feb 6, 2014 at 8:25 • Also, I get an error with your script. "...the parameter name 'p' is ambiguous..." with regards to Read-Host. – Iszi Commented Feb 6, 2014 at 8:29 # Ruby, 9490 82 chars p "The hypotenuse of this right triangle is %.3f"%(Math.sqrt(gets.to_i**2+gets.to_i**2))  Update (thanks for the comments): p "The hypotenuse of this right triangle is %.3f"%(gets.to_i**2+gets.to_i**2)**0.5  • You could save a few chars if you use a**0.5 instead of lengthy Math.sqrt(a). And the space after p can also be removed. Commented Feb 16, 2014 at 11:41 • And you do not need parenthesis in %(Math...). Commented Feb 16, 2014 at 11:46 # Whispers v2, 133, 93 bytes > Input > Input > "The hypotenuse of this right triangle is %.3f" >> 1⊿2 >> 3%4 >> Output 5  Try it online! The major part of this program is calculating the decimal point's index and truncating to 3 digits. -40 bytes from Leo! • Or you could "cheat" :) tio.run/##K8/ILC5ILSo2@v/… – Leo Commented Feb 8, 2021 at 21:45 • That's a thing?! Commented Feb 9, 2021 at 2:40 • Apparently % directly calls % from python, Jo King found this out – Leo Commented Feb 9, 2021 at 2:49 ## MATLAB 79 74 @(a,b)sprintf('The hypotenuse of this right triangle is %.3f',norm([a b]))  # Python 2.7 - 80 chars print'The hypotenuse of this right triangle is %.3f'%(input()**2+input()**2)**.5  • I don't think this does 3 decimal places...? Commented Feb 5, 2014 at 17:22 • It's my fault, I've corrected, thanks. Commented Feb 5, 2014 at 17:39 # C++ - 90 void h(int a,int b){printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}  • pow(a,2) when you can do a*a? I'm also not sure I understand the purpose of the floor and the +.5 and the multiply and divide by 1000 Commented Feb 5, 2014 at 16:48 • @Cruncher The floor is to set the decimal place to .3 places. I am reworking it right now, and will include your suggestion. – user10766 Commented Feb 5, 2014 at 16:51 • There is a hypot(a,b) which will save you three characters. – user15259 Commented Feb 5, 2014 at 18:03 • @YiminRong Cool! – user10766 Commented Feb 5, 2014 at 19:16 # Perl 6 (68 74 bytes) {printf "The hypotenuse of this right triangle is %.3f ",sqrt [+] @_ X**2}  {} declares a lambda function. [+] is sum operator, X** is cross power operator (for example, 1, 2 X+ 10, 20 gives 11, 21, 12, 22). In this case, cross power operator takes one argument, so the result has the same length as @_. @_ contains all function arguments. If it's disallowed to have function that may take wrong number of arguments (unsafe), it's possible to replace [+] @_ X**2 with $^a**2+$^b**2, where $^a and $^b are placeholder arguments. • How would you limit to 3 decimal places? Commented Feb 5, 2014 at 17:25 • @JoachimIsaksson: I fail at reading. Should be fixed now. – null Commented Feb 5, 2014 at 19:22 Javascript (97) x=prompt;a=x(),b=x();x('The hypotenuse of this right triangle is '+Math.sqrt(a*a+b*b).toFixed(3))  • .toFixed .. thank you! learned something new :) Commented Feb 7, 2014 at 23:37 ## C, 100 chars (beats the other C solution by 1!) A ridiculously inefficient algorithm. x;f(a,b){for(;x-a*a-b*b;x=rand());printf("The hypotenuse of this right triangle is %.3f",sqrt(x));}  • Sorry, but you've written "the" instead of "this", so if you correct that it's the same length ;P Commented Feb 5, 2014 at 23:32 • @daniero Ok, found a fix, now still one char down :) Commented Feb 5, 2014 at 23:46 • In the Borland C compiler it would not compile... – user58988 Commented Oct 23, 2017 at 10:22 ## DELPHI / PASCAL ### With indent (157) program p; {$APPTYPE CONSOLE}
var a,b:integer;
begin
readln(a,b);
writeln('the hypotenuse of this right triangle is',sqrt(b*b+a*a):2:3);
end.

• ah man, i had the exact same :( Commented Feb 6, 2014 at 9:08
• to late for an edit, so again.. Edit: You can get 2 characters off by changing integer to int16 You dont have to include the first 2 lines for your answer, and you can remove whitespace. doing all that gives you 106 characters. Commented Feb 6, 2014 at 9:15

## EcmaScript 6, 82 79

f=(a,b)=>"The hypotenuse of this right triangle is "+Math.hypot(a,b).toFixed(3)


Usage:

f(3, 5)
> "The hypotenuse of this right triangle is 5"


Update: Switch to Math.hypot()

Golfscript (69 67 66 65)

This would be much easier if floating point was actually supported without resorting to workarounds... :)

~'The hypotenuse of this right triangle is '@.*@.*+2-1??+.'.'?4+<

• why are you doing 2.!~ when 2-1 is shorter? Commented Feb 6, 2014 at 15:38
• @McKay Good question, I always getthe difference between 2- 1 and 2-1 wrong, so was probably temporarily confused :) Fixed, thanks. Commented Feb 6, 2014 at 16:16

# Python 2 (79)

def p(a,b):print'The hypotenuse of this right triangle is %.3d'%((a*a+b*b)**.5)

• Dispense with math for some savings. (a*a+b*b)**.5 Commented Feb 17, 2014 at 15:50
• Since the body of your function is a single statement, it can be on the same line as the def saving a newline and an indent. Commented Feb 17, 2014 at 16:30

# AWK — 84 78 characters

awk '{printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5}'


Thanks to Wasi for suggesting ^ operator and removing ()!

e.g.

$echo 3 4 | awk '{printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5}' The hypotenuse of this right triangle is 5.000  • You can golf it further {printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5} – Wasi Commented Feb 6, 2014 at 6:38 # PowerShell: 111 Golfed Code 1..2|%{sv$_ (read-host)};"The hypotenuse of this right triangle is $("{0:N3}"-f[math]::sqrt($1/1*$1+$2/1*$2))"  Walkthrough 1..2|%{sv$_ (read-host)}; Gets two inputs interactively from the user, and stores them in $1 and$2. Might be able to cut some length by using arguments or pipeline inputs instead.

"The hypotenuse of this right triangle is Required text in the output, per the challenge specifications.

$(...)" Encapsulated code block will be processed as script before being included in the output. "{0:N3}"-f Formats output from the next bit of code as a number with exactly three digits after the decimal point. [math]::sqrt(...) Gets the square root of the encapsulated value. $1/1*$1+$2/1*\$2 Serves as our "a^2+b^2". Multiplying a number by itself is the shortest way to square it in PowerShell, but the variables need to be divided by 1 first to force them to integers. Otherwise, they are treated as text and 3*3+4*4 would be 3334444 instead of 25.

## JavaScript: 83

i=prompt,'The hypotenuse of this right triangle is '+Math.hypot(i(),i()).toFixed(3)


Currently the shortest JS implementation using stdin :D
Works only on Firefox 27.0+ (EcmaScript 6)

## JavaScript: 78

If we can use just two variables (as lot of scripts do here):

a=2,b=3,'The hypotenuse of this right triangle is '+Math.hypot(a,b).toFixed(3)

• whoooo .. .hypot. Good catch! Commented Feb 7, 2014 at 23:41

# dc, 55

3k?d*?d*+v[The hypotenuse of this right triangle is ]Pp


## Java, 112

(Also prints out a No Such Method error, though I'm not sure if this is against the rules)

class A{static{int a=1,b=1;System.out.printf("The hypotenuse of this right triangle is %.3f",Math.hypot(a,b));}}


## Java, 149

(No error)

class A{static{int a=1,b=1;System.out.printf("The hypotenuse of this right triangle is %.3f",Math.hypot(a,b));}public static void main(String[] a){}}


C#

Method Only (114)

void H(double a, double b)
{
Console.Write("The hypotenuse of this right triangle is {0:N3}", Math.Sqrt(a * a + b * b));
}


Complete Program (171)

using System;
class P
{
static void H(double a, double b)
{
Console.Write("The hypotenuse of this right triangle is {0:N3}", Math.Sqrt(a * a + b * b));
}
static void Main()
{
H(3, 4);
}
}


Complete Program (without using method - 141)

using System;class P{static void Main(){double a=3,b=4;Console.Write("The hypotenuse of this right triangle is {0:N3}",Math.Sqrt(a*a+b*b));}}

• Heres my complete program. 141 chars...you can save a few chars using the formatstring overload of write using System;class P{static void Main(){double a=3,b=4;Console.Write("The hypotenuse of this right triangle is {0:N3}",Math.Sqrt(aa+bb));}} Commented Feb 6, 2014 at 3:27
• You can use string formatting in the Console.Write instead of calling ToString() to save 9 characters.
– Rik
Commented Feb 7, 2014 at 10:16

# JavaScript 118106 93

Unlike @micha's solution, mine takes in two variables via function and sends the alert of the result.

function(a,b){m=Math;c=d=>d*d,e=1e3;alert("The hypotenuse of this right triangle is "+m.round(m.sqrt(c(a)+c(b))*e)/e)}

function(a,b){e=1e3;alert("The hypotenuse of this right triangle is "+Math.round(Math.sqrt(a*a+b*b)*e)/e)}

Fat arrow functions to the rescue!

h=(a,b,e=1e3)=>"The hypotenuse of this right triangle is "+Math.round(Math.sqrt(a*a+b*b)*e)/e

• Could be shorter if you inline c(). Aliasing Math doesn't save bytes in your case. Commented Feb 6, 2014 at 10:26
• @Florent Ah, yes... one sec! Commented Feb 6, 2014 at 10:48

### c64 basic v2, 60 66 bytes

0inputa,b:?"The hypotenuse of this right triangle is";sQ(a*a+b*b)


Screenshot:

How to try it.

• should say "The hypotenuse of this right triangle is" Commented Sep 13, 2017 at 21:16
• @Mayube Sad :-( +6 byte :-( Post fixed. Commented Sep 13, 2017 at 21:17

# R, 61 76 bytes

cat("The hypotenuse of this right triangle is",round(sqrt(sum(scan()^2)),3))


cat displays its content to STDOUT.

The scan() function takes user's input from keyboard. This input exists as a vector, on which the ^2 is applied (^function is vectorized), and the sum() sums the elements of the vector. sqrt outputs the square-root, which is rounded to 3 decimal places by round(,3)

Thanks to @caird coinheringaahing for noticing that the previous answer didn't round.

• Does this "Keep c to only three decimal places."? Commented Oct 21, 2017 at 20:03
• @cairdcoinheringaahing : it does now ! Thanks ! Commented Oct 21, 2017 at 20:08

# OML, 57 bytes

"The hypotenuse of this right triangle is "shnhn+A6*N3eD


Try it online!

## Part 1

This simply outputs the string

"The hypotenuse of this right triangle is "s


## Part 2

hnhn+A6*N3eD
hn              take input and square it
hn            take another input and square it
+           add them
A6        push 10^6
*       multiply the sum with that number
N      take integer square root
3eD   output with three places of precision
implicit output


# Jelly, 32 characters

,²S½ær3µ,“¡ÆC⁷⁺ɱSoṿȤç½?⁶Ẏtḍỵŀ»ṚK


Try it online!

There is probably a better string compression that allows me to get around needing to join with spaces but I was having trouble finding it.

Explanation:

,²S½ær3µ,“...»ṚK    Example inputs: 3, 4
,                   Pair the inputs. Result: [3, 4]
²                  Square them. Result: [9, 16]
S                 Sum them. Result: 25
½                Get the square root of the sum. Result: 5
ær3             Round to 3 decimal places. Result: 5
µ            Take the result of that... Result: 5
“...»       ...and  the compressed string Result: "The hypotenuse of this right triangle is"
,           And put them into a pair. Result: [5, "The hypotenuse of this right triangle is"]
Ṛ     Reverse that. Result: ["The hypotenuse of this right triangle is", 5]
k    Join it with spaces. Result: "The hypotenuse of this right triangle is 5.0"
Implicit output.

• So long as only three decimal places means less than or equal to three decimal places, the output looks fine. Commented Oct 23, 2017 at 20:43