모든 일상

[C# / 백준] 1193번 문제 분수찾기 본문

코딩 공부/C#

[C# / 백준] 1193번 문제 분수찾기

통통푸린 2024. 6. 4. 14:32
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)가 주어진다.

출력

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

예제 입출력

코드
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            int num = int.Parse(Console.ReadLine());
            int sum = 0;
            int line_cnt = 0;
            int last_num = 0;
            while(num > sum) // 몇번째 대각선인지 알아내기
            {
                line_cnt++;
                sum += line_cnt;
            }
            for(int i = 1; i<line_cnt; i++) //해당 숫자의 이전 열 마지막 숫자 알아내기
            {
                last_num += i;
            }

            int index =  num - last_num; // 입력숫자 - 이전 열 마지막 숫자 = 입력한 숫자의 순서를 알아내기

            if (line_cnt % 2 == 1) // 홀수 대각선
            {
                Console.WriteLine((line_cnt - index + 1) + "/" + index);
            }
            else // 짝수 대각선
            {
                Console.WriteLine(index + "/" + (line_cnt-index+1)) ;
            }

            
        }
    }
}

이런식의 순서로 대각선이 채워진다.

짝수열 대각선은 분모는 커지고 분자는 작아지고, 홀수열 대각선은 분모가 작아지고 분자가 커집니다. 

1열에는 숫자 1개. 2열에는 2개 이렇게 열의 수와 열에 속하는 숫자의 개수가 같다. 

그래서 입력숫자 - 이전 열의 마지막 숫자 = Index 즉 입력숫자가 그 행에 몇번째 숫자 인지 알 수 있다. 

728x90
반응형