Algorithm
[백준] 1193 분수 찾기 (JAVA)
KMSEOP
2020. 5. 8. 10:51
728x90
문제
무한히 큰 배열에 다음과 같이 분수들이 적혀있다.
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)가 주어진다.
출력
첫째 줄에 분수를 출력한다.
입력1 : 14
출력1 : 2/4
코드
import java.util.Scanner;
public class no_1193 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int X = sc.nextInt();
int n = 2, count = 0;
String result = null;
loop:
while(true) {
count += (n-1);
if(X <= count) {
X = X - count + n -1;
if(n % 2 == 1) {
for(int j=0; j<n; j++) {
if(X == 0) {
result = j + "/" + (n-j);
break loop;
}
X -= 1;
}
}else {
for(int j=0; j<n; j++) {
if(X == 0) {
result = (n-j) + "/" + j;
break loop;
}
X -= 1;
}
}
}
n++;
}
System.out.println(result);
//모법답안
// Scanner sc = new Scanner(System.in);
// int X = sc.nextInt();
// int line = 0, count = 0;
// while(count < X) {
// line++;
// count = line * (line+1) / 2;
// }
// if(line % 2 != 0){
// int top = 1 + (count - n);
// int bottom = line - (count - n);
// System.out.println(top + "/" + bottom);
// }else {
// int bottom = 1 + (count - n);
// int top = line - (count - n);
// System.out.println(top + "/" + bottom);
// }
}
}
728x90