본문 바로가기
알고리즘

[JAVA]백준 1735번: 분수 합

by Kwoncorin 2020. 11. 14.
728x90

www.acmicpc.net/problem/1735

 

1735번: 분수 합

첫째 줄과 둘째 줄에, 각 분수의 분자와 분모를 뜻하는 두 개의 자연수가 순서대로 주어진다. 입력되는 네 자연수는 모두 30,000 이하이다.

www.acmicpc.net

 

1. 문제 설명

 

두 분수가 주어질 때 두 분수의 합을 기약 분수로 출력하는 문제이다.

 

두 개의 분모들끼리의 최소공배수를 구하고 이를 두 분수의 합의 분모로 한다.

 

그리고 두 분수들의 분자들을 분모들이 두 분수의 합의 분모가 되기 위해 곱해지는 수만큼 분자들을 곱하고 합을 구한다.

 

그 후 두 분수의 합의 분수의 분모와 분자의 최대공약수를 구해 그 수를 나누어 기약 분수를 만든다.

 

 

 

2. 코드

 

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {


    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);


        //one 분자 two 분모
        int A_one,A_two,B_one,B_two;
        int total_one,total_two;

        A_one=scan.nextInt();
        A_two=scan.nextInt();
        B_one=scan.nextInt();
        B_two=scan.nextInt();

        total_two=A_two*B_two/gcd_change(A_two,B_two);
        total_one=A_one*(total_two/A_two)+B_one*(total_two/B_two);

        int total_gcd=gcd_change(total_one,total_two);

        System.out.println(total_one/total_gcd+" "+total_two/total_gcd);

        scan.close();
    }

    public static int gcd_change(int a,int b){
        if(a<b)
            return gcd(b,a);
        return gcd(a,b);
    }

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



}
728x90