Post

[백준] 1735번 - 분수 합 [Java][C++]

[백준] 1735번 - 분수 합 [Java][C++]

문제 링크


1. 문제 풀이

두 분수의 합을 기약분수의 형태로 구하는 문제로 두 분수의 합은 $\dfrac{A}{B} + \dfrac{C}{D} = \dfrac{A \times D + B \times C}{B \times D}$ 임을 이용하고 기약분수는 분자와 분모의 최대공약수로 나누면 됨을 이용하면 된다.


2. 코드

1. 유클리드 호제법 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.*;
import java.util.*;

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

        st = new StringTokenizer(br.readLine());
        int A = Integer.parseInt(st.nextToken());
        int B = Integer.parseInt(st.nextToken());

        st = new StringTokenizer(br.readLine());
        int C = Integer.parseInt(st.nextToken());
        int D = Integer.parseInt(st.nextToken());

        int numerator = A * D + B * C;  // 분자
        int denominator = B * D;  // 분모
        int gcd = gcd(numerator, denominator);
        System.out.printf("%d %d", numerator / gcd, denominator / gcd);
    }

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

2. 유클리드 호제법 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int a, b, c, d;
    cin >> a >> b >> c >> d;

    int numerator = a * d + b * c;  // 분자
    int denominator = b * d;        // 분모
    int g = gcd(numerator, denominator);

    cout << numerator / g << ' ' << denominator / g;
}

3. 풀이 정보

1. 유클리드 호제법 [Java]

언어시간메모리코드 길이
Java 11108 ms14536 KB857 B

2. 유클리드 호제법 [C++]

언어시간메모리코드 길이
C++ 170 ms2020 KB355 B

This post is licensed under CC BY 4.0 by the author.