백준 1735번 분수 합 JAVA

YB·2025년 12월 15일

링크텍스트

설명

통분하고 약분하면 되는 문제이다.
시간복잡도: O(logN), 공간복잡도: O(logN)

회독

  • [ x ] 1회
  • 2회
  • 3회

코드

import java.io.*;
import java.util.*;

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

        int A1 = Integer.parseInt(st.nextToken()); // 분자
        int B1 = Integer.parseInt(st.nextToken()); // 분모

        st = new StringTokenizer(br.readLine());
        int A2 = Integer.parseInt(st.nextToken());
        int B2 = Integer.parseInt(st.nextToken());

        int sum1 = (A1*B2)+(A2*B1);
        int sum2 = B1*B2;

        if(GCD(sum1,sum2)!=1){
            int gcd = GCD(sum1,sum2);
            sum1/=gcd;
            sum2/=gcd;
        }

        System.out.println(sum1 + " " + sum2);
  
    }

    public static int GCD(int a, int b){
        if(b==0) return a;
        return GCD(b,a%b);
    }
}

profile
안녕하세요

0개의 댓글