백준 1735

김경욱·2025년 8월 14일

백준

목록 보기
44/121

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int[] up = new int[2];
    int[] down = new int[2];

    StringTokenizer st1 = new StringTokenizer(br.readLine());
    up[0] = Integer.parseInt(st1.nextToken());
    down[0] = Integer.parseInt(st1.nextToken());

    StringTokenizer st2 = new StringTokenizer(br.readLine());
    up[1] = Integer.parseInt(st2.nextToken());
    down[1] = Integer.parseInt(st2.nextToken());



   int gcd1 =  gcd(down[0],down[1]);
   int lcm = down[0]*down[1] / gcd1;

    int resultDown=0;
    int resultUp=0;




resultDown = lcm;

resultUp = up[0]*(lcm/down[0])+up[1] *(lcm/down[1]);


int finance = gcd(resultDown,resultUp);
resultUp /= finance;
resultDown /= finance;

    System.out.println(resultUp+" "+resultDown);









}

    public static int gcd(int a, int b)  // 18 ,24
    {
        while(b!=0)
        {
            int temp = b;  // temp = 24   temp = 18  temp = 6
            b = a % b;  // b = 18     b = 6     b = 0
            a = temp; // a = 24     a  =  18   a = 6
        }

        return a;
    }

}

어려운 문제였다. StringTokenizer는 배열로 만드는 것이 어려워 따로 2개를 만들었다. gcd메서드를 이용해 최대 공약수를 구한 후 lcm이라는 최소 공배수를 구한 후 lcm을 분모에 분자에는 분자*(분모/최대 공약수)를 넣어 최종 값을 구하는데 이것을 또 약분해야 해서 구한 분자와 분모의 최대 공약수를 또 구하고 이걸 나눈 후의 값이 답이다. 수학 문제를 푸는 기분이다..

0개의 댓글