알고리즘
백준 1735번 분수 합 C++
영춘권의달인
2023. 2. 6. 12:22
https://www.acmicpc.net/problem/1735
1735번: 분수 합
첫째 줄과 둘째 줄에, 각 분수의 분자와 분모를 뜻하는 두 개의 자연수가 순서대로 주어진다. 입력되는 네 자연수는 모두 30,000 이하이다.
www.acmicpc.net
유클리드 알고리즘을 이용해서 최대공약수를 구해서 기약분수를 구한다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int getGcd(int a, int b) {
if (b == 0) return a;
return getGcd(b, a % b);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int a1, b1, a2, b2;
cin >> a1 >> b1;
cin >> a2 >> b2;
int numerator1 = a1 * b2;
int numerator2 = a2 * b1;
int numerator = numerator1 + numerator2;
int denominator = b1 * b2;
int gcd = getGcd(numerator, denominator);
cout << numerator / gcd << " " << denominator / gcd;
}