본문 바로가기
알고리즘

[ 백준 1193 ] 분수찾기

by 데구르르르 2021. 3. 23.

문제

무한히 큰 배열에 다음과 같이 분수들이 적혀있다.

1/1 1/2 1/3 1/4 1/5
2/1 2/2 2/3 2/4
3/1 3/2 3/3
4/1 4/2
5/1

이와 같이 나열된 분수들을 1/1 -> 1/2 -> 2/1 -> 3/1 -> 2/2 -> … 과 같은 지그재그 순서로 차례대로 1번, 2번, 3번, 4번, 5번, … 분수라고 하자.

X가 주어졌을 때, X번째 분수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 X(1 ≤ X ≤ 10,000,000)가 주어진다.


출력

첫째 줄에 분수를 출력한다.

예제 입력 예제 출력
14 2/4



[ JAVA ]

package baekjoon;
import java.util.*;
public class baekjoon_1193 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int count = 1;
int sum = 1;
count ++;
while(num >= sum + count ) {
sum += count;
count ++;
}
int rest = num - sum;
if(rest == 0) {
int a = 1;
int b = --count;
if(count%2 ==1) {
System.out.println(a+"/"+b);
}else {
System.out.println(b+"/"+a);
}
}else {
int a = count;
int b = 1;
for(int i=1; i<rest; i++) {
a--;
b ++;
}
if(count %2 ==1) {
System.out.println(a+"/"+b);
}else {
System.out.println(b+"/"+a);
}
}
}
}

댓글