[백준 | Javascript] 1193

박기영·2022년 6월 27일
0

백준

목록 보기
56/127

기본 수학1 3단계
1193번. 분수찾기

문제

무한히 큰 배열에 다음과 같이 분수들이 적혀있다.
참고 이미지
이와 같이 나열된 분수들을 1/1 → 1/2 → 2/1 → 3/1 → 2/2 → … 과 같은 지그재그 순서로 차례대로 1번, 2번, 3번, 4번, 5번, … 분수라고 하자.
X가 주어졌을 때, X번째 분수를 구하는 프로그램을 작성하시오.

입력

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

출력

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

예제 입출력

예제 입력 1

1

예제 출력 1

1/1

예제 입력 2

2

예제 출력 2

1/2

예제 입력 3

3

예제 출력 3

2/1

예제 입력 4

4

예제 출력 4

3/1

예제 입력 5

5

예제 출력 5

2/2

예제 입력 6

6

예제 출력 6

1/3

solution

const fs = require('fs');
let input = Number(fs.readFileSync('/dev/stdin').toString());

let getSection = 0;

while(input > 0){  
  // input 값이 몇 번째 그룹에 속하는지 파악하기 위함
  // 7이 들어왔다면, (1) 6, (2) 4, (3) 1, (4) -3 이 될 것
  // 위 값은 매 반복마다의 (getSection) input 을 표현한 것
  // input > 0까지 반복하므로 getSection은 3이 됨
  // 문제 사진과 비교해 봤을 때 input 7은 1/4를 의미하고, 4번째 구간에 존재한다.
  // 착각하면 안되는게, while은 들어오는 input이 양수일 때 동작하므로 (4) -3이 될 때까지는 동작한다.
  // input은 -3, getSection은 4 인 상태로 반복문 종료
  getSection++;
  input -= getSection;
}

// 주의
// 분수들은 순서가 지그재그 방향이라는 것을 기억하자.
// getSection이 홀수냐 짝수냐에 따라 진행 방향이 달라서 계산이 달라짐

// 1. getSection이 홀수인 경우
// 분자는 getSection부터 시작, 분모는 1부터 시작
// 분자는 getSection부터 -1씩 1까지 감소
// 분모는 1부터 +1씩 getSection까지 증가
// input 4 = 3/1
// (1) 3, (2) 1, (3) -2
// getSection 3, input -2
// input 5 = 2/2
// (1) 4, (2) 2, (3) -1
// getSection 3, input -1
// input 14 = 2/4
// (1) 13, (2) 11, (3) 8, (4) 4, (5) -1
// getSection 5, input -1

// 2. getSection이 짝수인 경우
// 분자는 1부터 시작, 분모는 getSection부터 시작
// 분자는 1부터 +1씩 getSection까지 증가
// 분모는 getSection부터 -1씩 1까지 감소
// input 3 = 2/1
// (1) 2, (2) 0
// getSection 2, input 0
// input 4 = 3/1
// (1) 3, 
// input 8 = 2/3
// (1) 7, (2) 5, (3) 2, (4) -2
// getSection 4, input -2

if(getSection % 2 == 1){
  const numerator = 1 - input;
  const denominator = getSection + input;
  console.log(`${numerator}/${denominator}`);
} else {
  const numerator = getSection + input;
  const denominator = 1 - input;
  console.log(`${numerator}/${denominator}`);
}
profile
나를 믿는 사람들을, 실망시키지 않도록

0개의 댓글