728x90
문제
분자 분모가 모두 자연수인 두 분수의 합 또한 분자 분모가 자연수인 분수로 표현할 수 있다.
두 분수가 주어졌을 때, 그 합을 기약분수의 형태로 구하는 프로그램을 작성하시오.
기약분수란 더 이상 약분되지 않는 분수를 의미한다.
입력
첫째 줄과 둘째 줄에, 각 분수의 분자와 분모를 뜻하는 두 개의 자연수가 순서대로 주어진다. 입력되는 네 자연수는 모두 30,000 이하이다.
출력
첫째 줄에 구하고자 하는 기약분수의 분자와 분모를 뜻하는 두 개의 자연수를 공백으로 구분하여 순서대로 출력한다.
예제 입력
2 7
3 5
예제 출력
31 35
// 코드
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception {
// Please Enter Your Code Here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int ASon = Integer.parseInt(st.nextToken());
int AMom = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int BSon = Integer.parseInt(st.nextToken());
int BMom = Integer.parseInt(st.nextToken());
int sonSum = (ASon*BMom) + (BSon*AMom);
int momSum = AMom * BMom;
int A = sonSum;
int B = momSum;
if(A < B) { // 분모, 분자 값이 바뀌었으므로 출력 시 반대로 출력해야 한다.
int temp = A;
A = B;
B = temp;
int a = A;
int b = B;
int gcd = -1;
int lcm = -1;
while(true) {
int r = a % b;
if(r == 0) {
gcd = b;
break;
}
a = b;
b = r;
}
if(gcd == 1) {
System.out.println(B + " " + A);
} else {
System.out.println( (B/gcd) + " " + (A/gcd));
}
} else {
int a = A;
int b = B;
int gcd = -1;
int lcm = -1;
while(true) {
int r = a % b;
if(r == 0) {
gcd = b;
break;
}
a = b;
b = r;
}
if(gcd == 1) {
System.out.println(A + " " + B);
} else {
System.out.println( (A/gcd) + " " + (B/gcd));
}
}
}
}
|
cs |
반응형