입력된 분수를 곱하여 새 분수(e/f)를 만들고, 분자 분모 각각을 분자 분모의 최대 공약수로 나누어주면 기약분수가 된다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
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 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 e = a * d + b * c;
int f = b * d;
int g = gcd(e, f);
System.out.println(e/g + " " + f/g);
}
public static int gcd(int A, int B) {
if (B == 0) return A;
return gcd(B, A % B);
}
}
'백준' 카테고리의 다른 글
[Java] 백준 9375번 - 패션왕 김해빈 (0) | 2024.04.23 |
---|---|
[Java] 백준 2630번 - 색종이 만들기 (0) | 2024.04.23 |
유클리드 호제법을 이용한 최소공배수 구하기 (0) | 2023.07.28 |
[Java] 백준 1253번 - 좋다 (1) | 2023.07.12 |
[Java] 백준 1940번 - 주몽 (0) | 2023.07.10 |