728x90
반응형
- 풀이 링크:
GitHub - xhaktmchl/Algorithm_study: 알고리즘 이론 및 문제풀이
알고리즘 이론 및 문제풀이. Contribute to xhaktmchl/Algorithm_study development by creating an account on GitHub.
github.com
#include <iostream>
#include <algorithm>
//#include <map> // 중복 x
//#include <string> // getline
using namespace std;
/*
[백준 1735 c++ O] 분수 합
문제:
접근:
시간복잡도: n
풀이:
//1.입력
//2.분수의 합
//3.기약분수로 만들기
*/
int up1, up2, down1, down2;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
//1.입력
cin >> up1 >> down1;
cin >> up2 >> down2;
//2.분수의 합
int up = up1 * down2 + up2 * down1;
int down = down1 * down2;
//3.기약분수로 만들기
for (int i = 30000; i >= 1; i--) {
if (up % i == 0 && down % i == 0) {
up /= i;
down /= i;
}
}
cout << up << " " << down << '\n';
return 0;
}
-풀이2: 유클리드 (최대공약수 이용)
GitHub - xhaktmchl/Algorithm_study: 알고리즘 이론 및 문제풀이
알고리즘 이론 및 문제풀이. Contribute to xhaktmchl/Algorithm_study development by creating an account on GitHub.
github.com
#include <iostream>
#include <algorithm>
//#include <map> // 중복 x
//#include <string> // getline
using namespace std;
/*
[백준 1735 c++ OO] 분수 합
문제:
접근:
시간복잡도: n
풀이:1
//1.입력
//2.분수의 합
//3.기약분수로 만들기
풀이2: 최대공약수(유클리드 호제법) 으로 두 수 나누기
*/
int up1, up2, down1, down2;
// 유클리드 호제법: 최대 공약수 구하기
int gcd(int a, int b) {
if (b > a) {
int tp = b;
b = a;
a = tp;
}
int c;
while (b) {
c = a % b;
a = b;
b = c;
}
return a;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
//1.입력
cin >> up1 >> down1;
cin >> up2 >> down2;
//2.분수의 합
int up = up1 * down2 + up2 * down1;
int down = down1 * down2;
//3.기약분수로 만들기 : 최대공약수로 두 수 나누기
int gcdNum = gcd(up, down);
cout << up / gcdNum << " " << down / gcdNum << '\n';
return 0;
}
반응형
'Algorithm_BOJ(백준) > 수학(Math)' 카테고리의 다른 글
[백준 1934 c++ O] 최소공배수 (0) | 2023.02.20 |
---|---|
[백준 10610 c++ V] 30 (0) | 2023.01.12 |
[백준 10430 c++ OO] 나머지 (0) | 2021.12.22 |
[백준 5543 c++ O] 상근날드 (0) | 2021.08.30 |
[백준 2587 c++ O] 대표값2 (0) | 2021.08.30 |