피타고라스 정리를 구현하는 가장 짧은 방법


14

피타고라스 정리 a² + b² = c²를 누가 좋아하지 않습니까? 값 a와 b를 취하고 "이 직각 삼각형의 빗변은"+ c를 출력하는 모든 언어로 가능한 가장 짧은 방법을 작성하십시오. c는 소수점 이하 세 자리 만 유지하십시오.


3
이것이 프로그래밍 퍼즐의 자격이됩니까?
DavidC

1
@DavidCarraher 문제 자체는 프로그래밍 퍼즐이 아닙니다. 그러나 목표는 솔루션을 골프화하는 것이므로 실제로 프로그래밍 퍼즐입니다.
Victor Stafusa 2014

3
최단 문자
Vik P

4
code-golf태그는 "Code-golf는 가장 적은 바이트 의 소스 코드 에서 특정 문제를 해결하기위한 경쟁" 이라고 명시 적으로 말합니다 . 스코어링 코드 골프 (바이트 대 문자)를 참조하십시오 .
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
문자를 저장하려면 "hypotenuse"의 철자를 수정하십시오.
Tim S.

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

3
제안을 구현하는 데 2 ​​년이 걸렸다.
mbomb007

위대함을 향한 것 같아요. 그리고 APL을 이길 두 바이트를 더 줄였습니다!
Timtech

-1 바이트 :Fix 3:R►Pr(X,Y
Khuldraeseth na'Barya

사용 Input을 요청 X하고하는 것은 Y재미의 종류이다. 허용 하면 빗자루 길이가 1 바이트로 표시되도록 PolarGCbefore 설정도 허용해야 합니까? 물론 커서를 움직일 때 및 값 이 더 이상 표시 되지 않지만 적절한 변수에 저장 됩니다. (우리가 다음 사용하지 않을 것이다, 그러나 그것은 카운트는 생각입니다.)InputRPolarGCXY
미샤 라브 로프

9

파이썬 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 : "Hypotenuse, 쉬운 질문입니다. 어제 밤에 유명한 파티가 있는데, 신문에서 High Party News라는 뉴스를 읽는다면"


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
유니 코드가 이것을 92 바이트처럼 만들지 않습니까?
Cruncher

@Cruncher 어제 질문 주석에서 물어 보았습니다. 바이트 수는 아닌 문자 수입니다.
Joachim Isaksson

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입니다."
Tomas

1
@Tomas 그것은 일종의 함수입니다. 테스트에서 보여주는 것처럼 스택에 매개 변수를 먼저 배치해야하거나 길을 호출하려는 경우 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));}

stdin에서 입력을 읽어야하는 경우 99

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

@Yimin Rong에게 큰 감사합니다!


1
hypot (a, b)가있어 3자를 절약 할 수 있습니다.

기능 내가 사용하는 컴파일 어떤 컴파일하지 않는 것이 GCC TCC 그 소리에 TIO 아마도 컴파일러의 정확한 버전을 하나의 #include 헤더 부족하고 제목에 ...
RosLuP

3

파워 쉘

내가 할 수 있는지 확인하기 위해 ...

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
잘 했어. 내 솔루션으로 바빠서이 작업을 수행 한 것처럼 보입니다. 이는 약 62자를 능가합니다. 나중에 참조 할 수 있도록 Code Golf 답변은 "골프"로 표시되고 "점수"가 포함됩니다. "골프 (Golfing)"는 짧은 별칭, 구문 트릭 및 언어 규칙을 확장하는 다른 방법을 사용하여 문자 길이를 줄이기 위해 모든 노력을 기울여야한다는 것을 의미합니다. 가능한 경우 불필요한 공백을 제거해야합니다 (솔루션에서 제거 할 수있는 공백이 3 개 이상 있어야 함). 이 경우 "점수"는 현재 문자 수입니다-현재 173.
Iszi

코드 골프 태그 위키, 도움말 센터의 다양한 부분 및 PowerShell 골프 팁 팁 스레드를 읽고 여기에서 골프 문제에 대한 경쟁적인 답변을 작성하는 방법에 대한 느낌을 얻으십시오.
Iszi

또한 스크립트에 오류가 있습니다. "... 파라미터 이름 'p'가 모호합니다 ..."와 관련하여 Read-Host.
Iszi

3

루비, 94 90 82 자

p "The hypotenuse of this right triangle is %.3f"%(Math.sqrt(gets.to_i**2+gets.to_i**2))

업데이트 (의견 감사) :

p "The hypotenuse of this right triangle is %.3f"%(gets.to_i**2+gets.to_i**2)**0.5

1
length a**0.5대신을 사용하면 몇 개의 문자를 저장할 수 있습니다 Math.sqrt(a). 그리고 이후의 공간 p도 제거 할 수 있습니다.
Nik O'Lai

1
그리고 괄호가 필요하지 않습니다 %(Math...).
Nik O'Lai

2

MATLAB 79 74

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


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)언제 할 수 a*a있습니까? 또한 바닥과 +.5의 목적을 이해하고 1000을 곱하고 1000으로 나눕니다
Cruncher

@Cruncher 바닥은 소수점 이하 자리를 .3 자리로 설정합니다. 지금 재 작업 중이며 제안 사항이 포함됩니다.

hypot (a, b)가있어 3자를 절약 할 수 있습니다.

@YiminRong 쿨!

2

펄 6 (68 74 바이트)

{printf "The hypotenuse of this right triangle is %.3f
",sqrt [+] @_ X**2}

{}람다 함수를 선언합니다. [+]합계 연산자, X**교차 전력 연산자 (예 : 1, 2 X+ 10, 20gives 11, 21, 12, 22)입니다. 이 경우 교차 전력 연산자는 하나의 인수를 취하므로 결과의 길이는와 같습니다 @_. @_모든 함수 인수를 포함합니다.

가 (안전하지 않은) 인수의 잘못된 번호를 취할 수있다 기능을하도록 허용 있다면, 그것을 대체하는 것이 가능 [+] @_ X**2하여 $^a**2+$^b**2, 어디 $^a$^b자리 표시 자 인수입니다.


2
소수점 이하 3 자리까지 어떻게 제한 하시겠습니까?
Joachim Isaksson

@JoachimIsaksson : 읽지 못했습니다. 지금 수정해야합니다.
Konrad Borowski 2019

2

자바 스크립트 (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

dc, 55

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

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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.