Найкоротший метод реалізації теореми Піфагора


14

Хто не любить теорему піфагора a² + b² = c²? Написати найкоротший метод можна будь-якою мовою, яка набирає значення a і b, і надрукує "Гіпотенуза цього правильного трикутника" + c. Зберігайте c лише до трьох знаків після коми.


3
Чи кваліфікується це як головоломка програмування?
DavidC

1
@DavidCarraher Сама по собі проблема не є головоломкою програмування. Але оскільки мета полягає в тому, щоб гольф вирішити його, то це справді головоломка програмування.
Віктор Стафуса

3
найкоротший за персонажами
Vik P

4
code-golfТег явно говорить «Code-гольф є конкуренція , щоб вирішити ту чи іншу проблему в найменшу кількість байт вихідного коду.» Див. Розділ Скорочуючий код гольфу (байти проти символів) .
res

1
@res: Виправлено :-p
Timwi

Відповіді:


15

APL (54)

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

Тест:

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

Пояснення:

  • ⎕*2: підняти значення на вході до другої потужності
  • +/: взяти суму
  • .5*⍨: підняти результат до 0,5-ї потужності
  • 3⍕: круглий до 3 знаків після коми

Йдеться про неперевершений
Cruncher

@Cruncher: Я намагався кодувати рядок, але не міг отримати рутинну програмування досить маленькою.
marinus

За принципом голубиного отвору, я думаю, вам було б дуже важко (можливо, неможливо. Потрібно бути неможливим хоча б деякі струни), намагаючись стиснути струну. Можливо, якщо рядок мав якийсь логічний зразок, але це, здається, не так. Мені цікаво побачити спроби, які у вас були досі
Cruncher

7
Виправте написання «гіпотенузи», щоб зберегти персонаж.
Тім С.

1
@Cruncher: Насправді я побив це у Sclipting ...
Timwi

11

TI-BASIC, 76 55 53 52 байт

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

Ні, дужки, що закриваються, не потрібні. Також менше байтів, ніж відповідь APL :)


1
Може бути R▶Pr(A,B.
lirtosiast

3
2 роки на реалізацію пропозиції, lol
mbomb007

Гадаю, велич, я думаю. І я просто поголив ще два байти, щоб перемогти APL!
Timtech

-1 байт:Fix 3:R►Pr(X,Y
Хулдраесет на’Барія

Використовувати Inputпросити Xі Yє наче смішним. Якщо ми це дозволимо, чи слід також дозволити встановлення PolarGCраніше Input, щоб довжина гіпотенузи була задана однобайтом R? Щоправда, PolarGCзначення Xта Yбільше не відображаються, коли ми переміщуємо курсор навколо, але вони все ще зберігаються у відповідних змінних. (Що б ми тоді ніколи не використовували, але ця думка враховує.)
Міша Лавров

9

Python 2.7 - 76 символів

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

Пояснення

| a + ib | = √ (a 2 + b 2 ) = c

==> a 2 + b 2 = c 2

PJ на гіпотенузу

Вчитель: "Чи можете ви сказати мені, що таке гіпотенуза?"

LJ: "Гіпотенуза, легке запитання. Якщо вчора ввечері була гучна вечірка, і ви читаєте її в газеті, що називається" Новини високої партії "


8

Сліптінг , 46 символів

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

Очікує введення у вигляді двох чисел (можуть бути дробовими!), Розділених пробілом.

Це коротше, ніж APL, незважаючи на те, що потрібно використовувати кілька незручних хитрощів.

Пояснення

글坼 | 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
не Unicode робить це як 92 байти?
Cruncher

@Cruncher Я вчора запитав у коментарях запитання, що враховує кількість символів, а не кількість байт.
Йоахім Ісакссон

3

DC 54

Тангентує бал відповіді APL!

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

Тест:

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

насправді не працює для мене. dc -e '2^r2^+3kv[The hypotenuse of this right triangle is ]Pp'не чекає жодного введення, друкується "dc: stack empty"3 рази, а потім "Гіпотенуза цього правильного трикутника становить 2 000".
Томаш

1
@Tomas це свого роду функція aa; вам потрібно поставити параметри в стек спочатку, як я показую в тесті, або якщо ви хочете викликати свій шлях, це було б dc -e '3 4 2^r2^+3kv[...там, де 3 і 4 - параметри.
daniero

3

C, 77 або 99

77 символів, якщо введенням можуть бути лише аргументи функції:

f(a,b){printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}

99, якщо вхід повинен бути прочитаний з stdin:

a,b;f(){scanf("%d %d",&a,&b);printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}

Велике спасибі @Yimin Rong!


1
Існує гіпота (a, b), яка врятує вас трьох символів.

Ця функція не компілювати будь-яку компіляцію, я використовую gcc tcc clang в tio ... можливо, не вистачає одного заголовка #include, а в заголовку точна версія компілятора
RosLuP

3

Powershell

Просто, щоб побачити, чи можу я ...

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

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

Also, I get an error with your script. "...the parameter name 'p' is ambiguous..." with regards to Read-Host.
Iszi

3

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

1
And you do not need parenthesis in %(Math...).
Nik O'Lai



2

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
Cruncher

@Cruncher The floor is to set the decimal place to .3 places. I am reworking it right now, and will include your suggestion.

There is a hypot(a,b) which will save you three characters.

@YiminRong Cool!

2

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
How would you limit to 3 decimal places?
Joachim Isaksson

@JoachimIsaksson: I fail at reading. Should be fixed now.
Konrad Borowski

2

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 :)
micha

2

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
daniero

@daniero Ok, found a fix, now still one char down :)
user12205

In the Borland C compiler it would not compile...
RosLuP

2

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
ah man, i had the exact same :(
Teun Pronk

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

2

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


2

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.


why are you doing 2.!~ when 2-1 is shorter?
McKay

@McKay Good question, I always getthe difference between 2- 1` and 2-1 wrong, so was probably temporarily confused :) Fixed, thanks.
Joachim Isaksson

2

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
Steven Rumbalski

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

1

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

1

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.


1

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!
micha


1

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){}}

1

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
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));}}
Tim Bailey

1
You can use string formatting in the Console.Write instead of calling ToString() to save 9 characters.
Rik

1

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
Could be shorter if you inline c(). Aliasing Math doesn't save bytes in your case.
Florent

@Florent Ah, yes... one sec!
WallyWest


1

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."?
caird coinheringaahing

@cairdcoinheringaahing : it does now ! Thanks !
Frédéric

1

ARBLE, 73 bytes

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

Try it online!


1
@H.PWiz I must say, for a challenge that should just be sqrt(a^2+b^2), this has a lot of unnecessary boilerplate.
ATaco

1

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

1

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.
Engineer Toast
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.