알고리즘/백준

[java] 백준 4153번 직각삼각형

펄찌 2021. 7. 23. 21:14

마지막에 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;
    }
}

결과는...

 

반응형