![[java] 백준 4153번 직각삼각형](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbfBVlE%2FbtracZEQNDQ%2FylLWjeZ1C8qyWnw9fIxmxK%2Fimg.jpg)
[java] 백준 4153번 직각삼각형알고리즘/백준2021. 7. 23. 21:14
Table of Contents
마지막에 0 0 0 을 입력시켰을 때 반복문을 종료 시켜주면 되겠다 싶어 이런식으로 구현을 했고
Math.pow 함수를 쓰면 ex) Math.pow(3,2) => 3의 제곱인 9가 나오는 것이다.
그래서 아래와 같이 코드를 작성했다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
// 입력이 0 0 0 일때 반복문 탈출
if(a == 0 && b == 0 && c == 0){
break;
} else if (isRightTriangle(a, b, c)){
System.out.println("right");
} else {
System.out.println("wrong");
}
}
}
public static boolean isRightTriangle(int a, int b, int c) {
return (int)(Math.pow(a, 2) + Math.pow(b, 2) ) == (int)Math.pow(c, 2);
}
}
하지만...
왜죠...? 반례를 찾아보기 시작했다. 입력에서는 a < b < c 로 되어 있는걸 볼 수 있는데
입력에서 c가 항상 크지 않다.
그러면 경우의 수가 6가지가 나오는데 아래와 같이 코드를 수정했다.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
// 입력이 0 0 0 일때 반복문 탈출
if(a == 0 && b == 0 && c == 0){
break;
} else if (isRightTriangle(a, b, c)){
System.out.println("right");
} else {
System.out.println("wrong");
}
}
}
public static boolean isRightTriangle(int a, int b, int c) {
int a2 = (int)Math.pow(a, 2);
int b2 = (int)Math.pow(b, 2);
int c2 = (int)Math.pow(c, 2);
// 경우의 수
// a < b < c
// a < c < b
// b < a < c
// b < c < a
// c < a < b
// c < b < a
if( a < b && b < c)
return a2 + b2 == c2;
else if(a < c && c < b)
return a2 + c2 == b2;
else if(b < a && a < c)
return b2 + a2 == c2;
else if(b < c && c < a)
return b2 + c2 == a2;
else if(c < a && a < b)
return c2 + a2 == b2;
else if(c < b && b < a)
return c2 + b2 == a2;
else
return false;
}
}
결과는...
'알고리즘 > 백준' 카테고리의 다른 글
[java] 백준 2581번 소수 (0) | 2021.07.25 |
---|---|
[java] 백준 11653번 소인수분해 (9) | 2021.07.24 |
[java] 백준 1978번 소수 찾기 (2) | 2021.07.22 |
[java] 백준 10757번 큰 수 A+B (2) | 2021.07.21 |
[java] 백준 2839번 설탕 배달 (0) | 2021.07.20 |
@펄찌 :: Pearl's Story
펄의 일상이 궁금한 사람 요기~
즐거운 하루 되셨으면 좋겠습니다😊