반응형
https://www.acmicpc.net/problem/1735
1735번: 분수 합
첫째 줄과 둘째 줄에, 각 분수의 분자와 분모를 뜻하는 두 개의 자연수가 순서대로 주어진다. 입력되는 네 자연수는 모두 30,000 이하이다.
www.acmicpc.net
분수합 문제
두 분수의 합을 기약분수의 형태로 구하는 문제
#사용 알고리즘
수학
📌문제 접근 포인트
1. 단순 분수의 합을 구하는 방법은 A/B + C/D 라고 하면 A*D + B*C / B*D 이다.
2. 기약 분수로 나타내야 한다는 것은 두 수의 최대 공약수로 나누어야 한다는 뜻이다. 두 수의 최대 공약수를 구할 수 있도록 함수를 구성하자.
3. 각 분자와 분수를 최대 공약수로 나누면 해결!
⚙ 내가 푼 정답 코드
public class Main {
public static int GCD(int a, int b) {
if (a % b == 0) {
return b;
}
return GCD(b, a%b);
}
public static void main(String[] args) throws IOException {
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 numerator = A*D+B*C;
int denominator = B*D;
int gcd = GCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
System.out.println(numerator + " " + denominator);
}
}
반응형
'알고리즘 풀이 > 백준' 카테고리의 다른 글
[백준 17141] 연구소 2 (python) (0) | 2023.06.20 |
---|---|
[백준 11000] 강의실 배정 (python) (0) | 2023.06.18 |
[백준 1967] 트리의 지름(python) (0) | 2023.06.14 |
[백준 18870] 좌표 압축(Java) (0) | 2023.06.08 |
[백준 9084] 동전 (python) (0) | 2023.06.08 |
댓글