Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Who doesn't love the pythagorean theorem a²+b²=c²? 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.

share|improve this question
3  
Does this qualify as a programming puzzle? –  David Carraher Feb 5 at 16:51
    
@DavidCarraher The problem per se is no programming puzzle. But since the objective is to golf a solution for it, then it is indeed a programming puzzle. –  Victor Feb 5 at 19:46
3  
shortest in characters –  Vik P Feb 5 at 20:55
3  
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). –  r.e.s. Feb 6 at 12:47
1  
@r.e.s.: Fixed :-p –  Timwi Feb 6 at 14:55

40 Answers 40

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
share|improve this answer
    
This is about unbeatable –  Cruncher Feb 5 at 19:16
    
@Cruncher: I tried to encode the string but couldn't get the decoding routine small enough. –  marinus Feb 5 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 –  Cruncher Feb 5 at 20:38
5  
Correct the spelling of "hypotenuse" to save a character. –  Tim S. Feb 5 at 20:45
1  
@Cruncher: Actually, I beat it in Sclipting... –  Timwi Feb 6 at 15:04

Python 2.7 - 76 Characters

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

Explanation

|a+ib| = √(a2+b2)=c

==> a2+b2 = c2

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"

share|improve this answer
    
Technically this doesn't print anything, it just calculates the representation of that command. In a script it wouldn't otuput anything –  Lego Stormtroopr Feb 6 at 1:12

TI-BASIC, 76

Input A,B:Disp "THE HYPOTENUSE OF THIS RIGHT TRIANGLE IS ", round(√(A²+B²),3

No, a closing parentheses is not required.

share|improve this answer

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
各 | for each...
  갠方 | to the power of two
終
加 | add
감半方 | to the power of one half
갾밈乘 | multiply by 1000
增貶 | increment, then decrement (kludge for rounding)
껠矽 | insert '.' at 4th-last character position
녆둥긆둹댆뭴뉖멵댶넠닶눠덆둩댲걲늖덨덂건댦땡닦덬뉒걩댲밀⓶ | "The hypotenuse..."
share|improve this answer
2  
doesn't unicode make this like 92 bytes? –  Cruncher Feb 6 at 17:43
    
@Cruncher I asked yesterday up in the question comments, what counts is character count, not byte count. –  Joachim Isaksson Feb 6 at 21:55

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!

share|improve this answer
1  
There is a hypot(a,b) which will save you three characters. –  Yimin Rong Feb 5 at 18:03
    
Good to know. Thanks! –  Josh Feb 5 at 18:05

MATLAB 79 74

@(a,b)sprintf('The hypotenuse of this right triangle is %.3f',norm([a b]))
share|improve this answer

Python 2.7 - 80 chars

print'The hypotenuse of this right triangle is %.3f'%(input()**2+input()**2)**.5
share|improve this answer
    
I don't think this does 3 decimal places...? –  Joachim Isaksson Feb 5 at 17:22
    
It's my fault, I've corrected, thanks. –  nutria Feb 5 at 17:39

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.

share|improve this answer
2  
How would you limit to 3 decimal places? –  Joachim Isaksson Feb 5 at 17:25
    
@JoachimIsaksson: I fail at reading. Should be fixed now. –  xfix Feb 5 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))
share|improve this answer
    
.toFixed .. thank you! learned something new :) –  micha Feb 7 at 23:37

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
share|improve this answer
    
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". –  Tomas Feb 6 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. –  daniero Feb 6 at 14:03

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));}
share|improve this answer
    
Sorry, but you've written "the" instead of "this", so if you correct that it's the same length ;P –  daniero Feb 5 at 23:32
    
@daniero Ok, found a fix, now still one char down :) –  ace Feb 5 at 23:46

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))
share|improve this answer
1  
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 Feb 6 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 Feb 6 at 8:25
    
Also, I get an error with your script. "...the parameter name 'p' is ambiguous..." with regards to Read-Host. –  Iszi Feb 6 at 8:29

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.
share|improve this answer
1  
ah man, i had the exact same :( –  Teun Pronk Feb 6 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. –  Teun Pronk Feb 6 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()

share|improve this answer

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

A link to test it.

share|improve this answer
    
why are you doing 2.!~ when 2-1 is shorter? –  McKay Feb 6 at 15:38
    
@McKay Good question, I always get`the difference between 2- 1 and 2-1 wrong, so was probably temporarily confused :) Fixed, thanks. –  Joachim Isaksson Feb 6 at 16:16

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));}}
share|improve this answer
1  
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(a*a+b*b));}} –  Tim Bailey Feb 6 at 3:27
1  
You can use string formatting in the Console.Write instead of calling ToString() to save 9 characters. –  Rik Feb 7 at 10:16
    
Thanks Tim and Rik. I learnt a new thing from you guys. –  Merin Nakarmi Feb 7 at 20:23

Ruby, 94 90 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
share|improve this answer
1  
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. –  Nik O'Lai Feb 16 at 11:41
1  
And you do not need parenthesis in %(Math...). –  Nik O'Lai Feb 16 at 11:46

Javascript, 109

A=1,B=1,s=1e3,console.log("The hypotenuse of this right triangle is " + (Math.round(Math.sqrt(A*A+B*B)*s)/s))

Fiddledee

share|improve this answer
4  
with alert you could save 6 chars –  Fez Vrasta Feb 5 at 18:23
    
Down to 101: A=1,B=1,s=1e3;alert("The hypotenuse of this right triangle is "+(Math.round(Math.sqrt(A*A+B*B)*s)/s)) –  James Webster Feb 6 at 15:57
    
Using suggestions from other entries so far I get it to 90: A=1,B=1;alert("The hypotenuse of this right triangle is "+(Math.sqrt(A*A+B*B).toFixed(3))) Even less if you leave out alert –  micha Feb 8 at 0:03

C++ - 90

void h(int a,int b){printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}
share|improve this answer
    
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 –  Cruncher Feb 5 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. –  hosch250 Feb 5 at 16:51
    
There is a hypot(a,b) which will save you three characters. –  Yimin Rong Feb 5 at 18:03
    
@YiminRong Cool! –  hosch250 Feb 5 at 19:16

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
share|improve this answer
    
You can golf it further {printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5} –  Wasi Feb 6 at 6:38

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)
share|improve this answer
    
whoooo .. .hypot. Good catch! –  micha Feb 7 at 23:41

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){}}
share|improve this answer

JavaScript 118 106 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

share|improve this answer
1  
Could be shorter if you inline c(). Aliasing Math doesn't save bytes in your case. –  Florent Feb 6 at 10:26
    
@Florent Ah, yes... one sec! –  WallyWest Feb 6 at 10:48

Python 2 (79)

def p(a,b):print'The hypotenuse of this right triangle is %.3d'%((a*a+b*b)**.5)
share|improve this answer
    
Dispense with math for some savings. (a*a+b*b)**.5 –  Steven Rumbalski Feb 17 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. –  Steven Rumbalski Feb 17 at 16:30
    
Thanks for the tips! –  nyuszika7h Feb 17 at 18:12

Scala (95c)

import Math._;val x=sqrt(pow(a,2)+pow(b,2));f"The hypotenuse of this right triangle is $x%1.3g"
share|improve this answer

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.

share|improve this answer

Java : 223

   class l {
        public static void main(String[] args) {      
          new l().H(2,4);
        }   
        void H(float a, float b)
    {
        System.out.printf("The hypotenuse of this right triangle is %.3f",Math.hypot(a,b));
    }
    }
share|improve this answer
    
I brought this to 170 by making it a one liner, changing the method to a static: class h{public static void main(String[]args){H(2,4);}static void H(float a,float b){System.out.printf("The hypotenuse of this right triangle is %.3f",Math.hypot(a,b));}} –  Michaël Demey Feb 6 at 10:41
    
@Michaël Demey, hah, i didnt think of that changing the function to static . –  BeyondProgrammer Feb 6 at 11:25

PHP- 51 characters (only the Method)

<?$a=3;$b=4;echo"Hypotenus=".round(hypot($a,$b),3);

share|improve this answer
    
Isn't $a*$a+$b*$b good enough? –  Pierre Arlaud Feb 6 at 8:36
    
yeah it is. thanks . i've updated. –  Sp0T Feb 6 at 8:40
    
Save some bytes using hypot($a,$b) instead of sqrt($a*$a+$b*$b) –  Florent Feb 6 at 10:19
    
thanks. i didn't knew hypot was there in php. grt.. –  Sp0T Feb 6 at 10:25
2  
the long part of the code is the phrase "The hypotenuse of this right triangle is ", your code would be 82 –  Fez Vrasta Feb 6 at 12:28

Groovy : 78 Characters

a={x,y->printf"The hypotenuse of this right triangle is %.3f",Math.hypot(x,y)}

Assuming the task is just writing a method. If you need to take input parameters:

99 Characters

printf"The hypotenuse of this right triangle is %.3f",Math.hypot(args[0].toLong(),args[1].toLong())

I found two ways to it with the same length:

printf"The hypotenuse of this right triangle is %.3f",Math.sqrt(args.collect{it.toLong()**2}.sum())
share|improve this answer

dc, 55

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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