15
\$\begingroup\$

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.

\$\endgroup\$
7
  • 3
    \$\begingroup\$ Does this qualify as a programming puzzle? \$\endgroup\$
    – DavidC
    Feb 5 '14 at 16:51
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Feb 5 '14 at 19:46
  • 3
    \$\begingroup\$ shortest in characters \$\endgroup\$
    – Vik P
    Feb 5 '14 at 20:55
  • 6
    \$\begingroup\$ 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). \$\endgroup\$
    – r.e.s.
    Feb 6 '14 at 12:47
  • 1
    \$\begingroup\$ @r.e.s.: Fixed :-p \$\endgroup\$
    – Timwi
    Feb 6 '14 at 14:55

62 Answers 62

15
\$\begingroup\$

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

TI-BASIC, 76 55 53 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 :)

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Could be R▶Pr(A,B. \$\endgroup\$
    – lirtosiast
    Jun 8 '15 at 1:57
  • 3
    \$\begingroup\$ 2 years to implement a suggestion, lol. \$\endgroup\$
    – mbomb007
    Sep 13 '17 at 18:51
  • \$\begingroup\$ Destined for greatness, I guess. And I just shaved off two more bytes to beat APL! \$\endgroup\$
    – Timtech
    Sep 13 '17 at 19:38
  • \$\begingroup\$ -1 byte: Fix 3:R►Pr(X,Y \$\endgroup\$ Oct 21 '17 at 19:35
  • \$\begingroup\$ 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.) \$\endgroup\$ Oct 23 '17 at 3:12
9
\$\begingroup\$

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"

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

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..."
\$\endgroup\$
2
  • 2
    \$\begingroup\$ doesn't unicode make this like 92 bytes? \$\endgroup\$
    – Cruncher
    Feb 6 '14 at 17:43
  • \$\begingroup\$ @Cruncher I asked yesterday up in the question comments, what counts is character count, not byte count. \$\endgroup\$ Feb 6 '14 at 21:55
4
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ 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". \$\endgroup\$
    – Tomas
    Feb 6 '14 at 13:19
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – daniero
    Feb 6 '14 at 14:03
3
\$\begingroup\$

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!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ There is a hypot(a,b) which will save you three characters. \$\endgroup\$
    – user15259
    Feb 5 '14 at 18:03
  • \$\begingroup\$ 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 \$\endgroup\$
    – user58988
    Oct 23 '17 at 10:20
3
\$\begingroup\$

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))
\$\endgroup\$
3
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Iszi
    Feb 6 '14 at 8:23
  • \$\begingroup\$ 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. \$\endgroup\$
    – Iszi
    Feb 6 '14 at 8:25
  • \$\begingroup\$ Also, I get an error with your script. "...the parameter name 'p' is ambiguous..." with regards to Read-Host. \$\endgroup\$
    – Iszi
    Feb 6 '14 at 8:29
3
\$\begingroup\$

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Nik O'Lai
    Feb 16 '14 at 11:41
  • 1
    \$\begingroup\$ And you do not need parenthesis in %(Math...). \$\endgroup\$
    – Nik O'Lai
    Feb 16 '14 at 11:46
3
\$\begingroup\$

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!

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

MATLAB 79 74

@(a,b)sprintf('The hypotenuse of this right triangle is %.3f',norm([a b]))
\$\endgroup\$
2
\$\begingroup\$

Python 2.7 - 80 chars

print'The hypotenuse of this right triangle is %.3f'%(input()**2+input()**2)**.5
\$\endgroup\$
2
  • \$\begingroup\$ I don't think this does 3 decimal places...? \$\endgroup\$ Feb 5 '14 at 17:22
  • \$\begingroup\$ It's my fault, I've corrected, thanks. \$\endgroup\$ Feb 5 '14 at 17:39
2
\$\begingroup\$

C++ - 90

void h(int a,int b){printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}
\$\endgroup\$
4
  • \$\begingroup\$ 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 \$\endgroup\$
    – Cruncher
    Feb 5 '14 at 16:48
  • \$\begingroup\$ @Cruncher The floor is to set the decimal place to .3 places. I am reworking it right now, and will include your suggestion. \$\endgroup\$
    – user10766
    Feb 5 '14 at 16:51
  • \$\begingroup\$ There is a hypot(a,b) which will save you three characters. \$\endgroup\$
    – user15259
    Feb 5 '14 at 18:03
  • \$\begingroup\$ @YiminRong Cool! \$\endgroup\$
    – user10766
    Feb 5 '14 at 19:16
2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ How would you limit to 3 decimal places? \$\endgroup\$ Feb 5 '14 at 17:25
  • \$\begingroup\$ @JoachimIsaksson: I fail at reading. Should be fixed now. \$\endgroup\$ Feb 5 '14 at 19:22
2
\$\begingroup\$

Javascript (97)

x=prompt;a=x(),b=x();x('The hypotenuse of this right triangle is '+Math.sqrt(a*a+b*b).toFixed(3))
\$\endgroup\$
1
  • \$\begingroup\$ .toFixed .. thank you! learned something new :) \$\endgroup\$
    – micha
    Feb 7 '14 at 23:37
2
\$\begingroup\$

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));}
\$\endgroup\$
3
  • \$\begingroup\$ Sorry, but you've written "the" instead of "this", so if you correct that it's the same length ;P \$\endgroup\$
    – daniero
    Feb 5 '14 at 23:32
  • \$\begingroup\$ @daniero Ok, found a fix, now still one char down :) \$\endgroup\$
    – user12205
    Feb 5 '14 at 23:46
  • \$\begingroup\$ In the Borland C compiler it would not compile... \$\endgroup\$
    – user58988
    Oct 23 '17 at 10:22
2
\$\begingroup\$

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.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ ah man, i had the exact same :( \$\endgroup\$
    – Teun Pronk
    Feb 6 '14 at 9:08
  • \$\begingroup\$ 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. \$\endgroup\$
    – Teun Pronk
    Feb 6 '14 at 9:15
2
\$\begingroup\$

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

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

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.

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

Python 2 (79)

def p(a,b):print'The hypotenuse of this right triangle is %.3d'%((a*a+b*b)**.5)
\$\endgroup\$
2
  • \$\begingroup\$ Dispense with math for some savings. (a*a+b*b)**.5 \$\endgroup\$ Feb 17 '14 at 15:50
  • \$\begingroup\$ 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. \$\endgroup\$ Feb 17 '14 at 16:30
1
\$\begingroup\$

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

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.

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

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)
\$\endgroup\$
1
  • \$\begingroup\$ whoooo .. .hypot. Good catch! \$\endgroup\$
    – micha
    Feb 7 '14 at 23:41
1
\$\begingroup\$

dc, 55

3k?d*?d*+v[The hypotenuse of this right triangle is ]Pp
\$\endgroup\$
1
\$\begingroup\$

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){}}
\$\endgroup\$
1
\$\begingroup\$

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));}}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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));}} \$\endgroup\$
    – Tim Bailey
    Feb 6 '14 at 3:27
  • 1
    \$\begingroup\$ You can use string formatting in the Console.Write instead of calling ToString() to save 9 characters. \$\endgroup\$
    – Rik
    Feb 7 '14 at 10:16
1
\$\begingroup\$

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

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Could be shorter if you inline c(). Aliasing Math doesn't save bytes in your case. \$\endgroup\$
    – Florent
    Feb 6 '14 at 10:26
  • \$\begingroup\$ @Florent Ah, yes... one sec! \$\endgroup\$ Feb 6 '14 at 10:48
1
\$\begingroup\$

c64 basic v2, 60 66 bytes

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

Screenshot:

enter image description here

How to try it.

\$\endgroup\$
2
  • \$\begingroup\$ should say "The hypotenuse of this right triangle is" \$\endgroup\$
    – Skidsdev
    Sep 13 '17 at 21:16
  • \$\begingroup\$ @Mayube Sad :-( +6 byte :-( Post fixed. \$\endgroup\$
    – peterh
    Sep 13 '17 at 21:17
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Does this "Keep c to only three decimal places."? \$\endgroup\$ Oct 21 '17 at 20:03
  • \$\begingroup\$ @cairdcoinheringaahing : it does now ! Thanks ! \$\endgroup\$
    – Frédéric
    Oct 21 '17 at 20:08
1
\$\begingroup\$

ARBLE, 73 bytes

"The hypotenuse of this right triangle is "..floor(sqrt(a^2+b^2)*1e3)/1e3

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ @H.PWiz I must say, for a challenge that should just be sqrt(a^2+b^2), this has a lot of unnecessary boilerplate. \$\endgroup\$
    – ATaco
    Oct 22 '17 at 23:12
1
\$\begingroup\$

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
\$\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.