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.
67 Answers
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 power3⍕
: round to 3 decimal places
-
-
\$\begingroup\$ @Cruncher: I tried to encode the string but couldn't get the decoding routine small enough. \$\endgroup\$– marinusCommented Feb 5, 2014 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\$– CruncherCommented Feb 5, 2014 at 20:38
-
9\$\begingroup\$ Correct the spelling of "hypotenuse" to save a character. \$\endgroup\$– Tim S.Commented Feb 5, 2014 at 20:45
-
1\$\begingroup\$ @Cruncher: Actually, I beat it in Sclipting... \$\endgroup\$– TimwiCommented Feb 6, 2014 at 15:04
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 :)
-
1
-
3\$\begingroup\$ 2 years to implement a suggestion, lol. \$\endgroup\$– mbomb007Commented Sep 13, 2017 at 18:51
-
\$\begingroup\$ Destined for greatness, I guess. And I just shaved off two more bytes to beat APL! \$\endgroup\$– TimtechCommented Sep 13, 2017 at 19:38
-
\$\begingroup\$ -1 byte:
Fix 3:R►Pr(X,Y
\$\endgroup\$ Commented Oct 21, 2017 at 19:35 -
\$\begingroup\$ Using
Input
to ask forX
andY
is kind of hilarious. If we allow that, should we also allow settingPolarGC
beforeInput
, so that the length of the hypotenuse is given by the one-byteR
? Admittedly, withPolarGC
the values ofX
andY
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\$ 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
各 | 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..."
-
2\$\begingroup\$ doesn't unicode make this like 92 bytes? \$\endgroup\$– CruncherCommented Feb 6, 2014 at 17:43
-
\$\begingroup\$ @Cruncher I asked yesterday up in the question comments, what counts is character count, not byte count. \$\endgroup\$ 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
-
\$\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\$– TomasCommented Feb 6, 2014 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\$– danieroCommented 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!
-
1\$\begingroup\$ There is a hypot(a,b) which will save you three characters. \$\endgroup\$– user15259Commented Feb 5, 2014 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\$– user58988Commented 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))
-
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\$– IsziCommented Feb 6, 2014 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\$– IsziCommented Feb 6, 2014 at 8:25
-
\$\begingroup\$ Also, I get an error with your script. "...the parameter name 'p' is ambiguous..." with regards to
Read-Host
. \$\endgroup\$– IsziCommented Feb 6, 2014 at 8:29
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
-
1\$\begingroup\$ You could save a few chars if you use
a**0.5
instead of lengthyMath.sqrt(a)
. And the space afterp
can also be removed. \$\endgroup\$ Commented Feb 16, 2014 at 11:41 -
1\$\begingroup\$ And you do not need parenthesis in
%(Math...)
. \$\endgroup\$ 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
The major part of this program is calculating the decimal point's index and truncating to 3 digits. -40 bytes from Leo!
-
1\$\begingroup\$ Or you could "cheat" :) tio.run/##K8/ILC5ILSo2@v/… \$\endgroup\$– LeoCommented Feb 8, 2021 at 21:45
-
-
\$\begingroup\$ Apparently
%
directly calls%
from python, Jo King found this out \$\endgroup\$– LeoCommented 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
-
\$\begingroup\$ I don't think this does 3 decimal places...? \$\endgroup\$ Commented Feb 5, 2014 at 17:22
-
\$\begingroup\$ It's my fault, I've corrected, thanks. \$\endgroup\$ 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));}
-
\$\begingroup\$
pow(a,2)
when you can doa*a
? I'm also not sure I understand the purpose of the floor and the +.5 and the multiply and divide by 1000 \$\endgroup\$– CruncherCommented Feb 5, 2014 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\$– user10766Commented Feb 5, 2014 at 16:51
-
\$\begingroup\$ There is a hypot(a,b) which will save you three characters. \$\endgroup\$– user15259Commented Feb 5, 2014 at 18:03
-
\$\begingroup\$ @YiminRong Cool! \$\endgroup\$– user10766Commented 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.
-
2\$\begingroup\$ How would you limit to 3 decimal places? \$\endgroup\$ Commented Feb 5, 2014 at 17:25
-
\$\begingroup\$ @JoachimIsaksson: I fail at reading. Should be fixed now. \$\endgroup\$– nullCommented 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))
-
\$\begingroup\$ .toFixed .. thank you! learned something new :) \$\endgroup\$– michaCommented 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));}
-
\$\begingroup\$ Sorry, but you've written "the" instead of "this", so if you correct that it's the same length ;P \$\endgroup\$– danieroCommented Feb 5, 2014 at 23:32
-
\$\begingroup\$ @daniero Ok, found a fix, now still one char down :) \$\endgroup\$ Commented Feb 5, 2014 at 23:46
-
\$\begingroup\$ In the Borland C compiler it would not compile... \$\endgroup\$– user58988Commented 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.
-
1\$\begingroup\$ ah man, i had the exact same :( \$\endgroup\$ Commented Feb 6, 2014 at 9:08
-
\$\begingroup\$ to late for an edit, so again.. Edit: You can get 2 characters off by changing
integer
toint16
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\$ 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+<
-
\$\begingroup\$ why are you doing
2.!~
when2-1
is shorter? \$\endgroup\$– McKayCommented Feb 6, 2014 at 15:38 -
\$\begingroup\$ @McKay Good question, I always get
the difference between
2- 1` and2-1
wrong, so was probably temporarily confused :) Fixed, thanks. \$\endgroup\$ 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)
-
\$\begingroup\$ Dispense with
math
for some savings.(a*a+b*b)**.5
\$\endgroup\$ Commented Feb 17, 2014 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\$ 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
-
\$\begingroup\$ You can golf it further
{printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5}
\$\endgroup\$– WasiCommented 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)
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));}}
-
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\$ Commented Feb 6, 2014 at 3:27
-
1\$\begingroup\$ You can use string formatting in the Console.Write instead of calling ToString() to save 9 characters. \$\endgroup\$– RikCommented Feb 7, 2014 at 10:16
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
-
1\$\begingroup\$ Could be shorter if you inline
c()
. AliasingMath
doesn't save bytes in your case. \$\endgroup\$– FlorentCommented Feb 6, 2014 at 10:26 -
\$\begingroup\$ @Florent Ah, yes... one sec! \$\endgroup\$ 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:
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.
-
\$\begingroup\$ Does this "Keep c to only three decimal places."? \$\endgroup\$ Commented Oct 21, 2017 at 20:03
-
\$\begingroup\$ @cairdcoinheringaahing : it does now ! Thanks ! \$\endgroup\$– RudierCommented Oct 21, 2017 at 20:08
OML, 57 bytes
"The hypotenuse of this right triangle is "shnhn+A6`*N3eD
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
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.
-
\$\begingroup\$ So long as
only three decimal places
meansless than or equal to three decimal places
, the output looks fine. \$\endgroup\$ Commented Oct 23, 2017 at 20:43
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\$