Algorithm/Baekjoon
[백준] 4153번 : 직각삼각형 - Java
unknownomad
2022. 4. 1. 01:00
https://www.acmicpc.net/problem/4153
4153번: 직각삼각형
입력은 여러개의 테스트케이스로 주어지며 마지막줄에는 0 0 0이 입력된다. 각 테스트케이스는 모두 30,000보다 작은 양의 정수로 주어지며, 각 입력은 변의 길이를 의미한다.
www.acmicpc.net
알고리즘
- 피타고라스의 정리 활용
a2 = b2 + c2
풀이
1. Scanner
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();
if(x == 0 && y == 0 && z == 0) break;
/*
Math.sqrt()로 제곱근 구할 시
double 타입으로 제곱근 반환하는 과정에서
소수점 오차 발생할 수 있음
*/
if((x * x + y * y) == z * z) {
System.out.println("right");
}
else if(x * x == (y * y + z * z)) {
System.out.println("right");
}
else if(y * y == (z * z + x * x)) {
System.out.println("right");
}
else {
System.out.println("wrong");
}
}
}
}
2. BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int z = Integer.parseInt(st.nextToken());
if(x == 0 && y == 0 && z == 0) break;
if((x * x + y * y) == z * z) {
System.out.println("right");
}
else if(x * x == (y * y + z * z)) {
System.out.println("right");
}
else if(y * y == (z * z + x * x)) {
System.out.println("right");
}
else {
System.out.println("wrong");
}
}
}
}
3. BufferedReader + StringBuilder
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while(true) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int z = Integer.parseInt(st.nextToken());
if(x == 0 && y == 0 && z == 0) break;
if((x * x + y * y) == z * z) {
sb.append("right").append('\n');
}
else if(x * x == (y * y + z * z)) {
sb.append("right").append('\n');
}
else if(y * y == (z * z + x * x)) {
sb.append("right").append('\n');
}
else {
sb.append("wrong").append('\n');
}
}
System.out.println(sb);
}
}
성능
- BufferedReader + StringBuilder
- BufferedReader
- Scanner