brunch

You can make anything
by writing

C.S.Lewis

by fn nch Aug 09. 2019

백준 1193 : 분수찾기

이 문제를 풀 때는 규칙을 찾기 힘들어

https://spillmoon.tistory.com/3 이 분의 글에서 힌트를 얻어 풀었다.


1. 몇 번째 라인인지 찾는다.

1-1. 그 라인의 최소값 최대값을 찾는다.


최대값 : n*(n+1)/2

최소값 : n*(n+1)/2 - n + 1


2. 그 라인의 최대값을 -- 하면서 분모와 분자를 추리한다.

라인이 짝수 : 분모 = 1, 분자 = n

라인이 홀수 : 분모 = n, 분자 = 1


    public static void main(String[]args) {

        Scanner sc = new Scanner(System.in);

        int find = sc.nextInt();

        int n = 1;
        int max, min;

        // 원하는 숫자가 몇 번째 줄에 있는지 찾는다.
        while(true) {

            max = n*(n+1)/2;
            min = n*(n+1)/2-n+1;

            if ((min <= find) && (find <= max)) {
                break;
            }
            n++;
        }

        int up, down;

        // 라인이 홀수일 경우 분모 = 1, 분자 n
        if (n%2 == 1) {

            up = 1;
            down = n;

            while(true) {

                if (max == find) {
                    System.out.println(up + "/" + down);
                    break;
                }

                max--;
                down--;
                up++;

            }

        // 라인이 짝수일 경우 분모 = n, 분자 1
        } else {

            up = n;
            down = 1;

            while(true) {

                if (max == find) {
                    System.out.println(up + "/" + down);
                    break;
                }

                up--;
                down++;
                max--;

            }

        }
    }

작가의 이전글 백준 1712 : 손익분기점
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari