반응형
문제
https://www.acmicpc.net/problem/1735
1735번: 분수 합
첫째 줄과 둘째 줄에, 각 분수의 분자와 분모를 뜻하는 두 개의 자연수가 순서대로 주어진다. 입력되는 네 자연수는 모두 30,000 이하이다.
www.acmicpc.net
풀이
두 분수의 합을 기약분수 형태로 구하는 코드를 작성하면 됩니다
두 분수의 합은 어떻게 구할 수 있을까요?
23+56=2×6+3×53×6=2718
와같이 구할 수 있습니다.
이를 기약분수 형태로 나타내려면.. 27과 18의 최대공약수로 각각 나누어 주면 되겠죠?
최대공약수는 유클리드 호제법을 사용하여 구할 수 있습니다.
소스코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func gcd(_ a: Int, _ b: Int) -> Int { | |
if b == 0 { | |
return a | |
} | |
return gcd(b, a % b) | |
} | |
let input1 = readLine()!.split(separator: " ").map { Int($0)! } | |
let top1 = input1[0], bottom1 = input1[1] | |
let input2 = readLine()!.split(separator: " ").map { Int($0)! } | |
let top2 = input2[0], bottom2 = input2[1] | |
let bottom = bottom1 * bottom2 | |
let top = top1 * bottom2 + top2 * bottom1 | |
let div = gcd(top, bottom) | |
print(top / div, bottom / div) |
후기
최대공약수와 분수의 합을 구현한다면 쉽게 풀 수 있는 문제입니다.
반응형
'PS > 백준' 카테고리의 다른 글
[BOJ] 백준 4134 다음 소수 (Swift) (0) | 2023.03.16 |
---|---|
[BOJ] 백준 2485 가로수 (Swift) (0) | 2023.03.16 |
[BOJ] 백준 13241 최소공배수 (Swift) (0) | 2023.03.15 |
[BOJ] 백준 1934 최소공배수 (Swift) (0) | 2023.03.15 |
[BOJ] 백준 11729 하노이 탑 이동 순서 (Swift) (0) | 2023.03.15 |