[백준][Python] 1735. 분수 합
Silver Ⅲ 🔗1735. 분수 합
📝문제 요약
문제
분수 A/B는 분자가 A, 분모가 B인 분수를 의미한다. A와 B는 모두 자연수라고 하자.
두 분수의 합 또한 분수로 표현할 수 있다. 두 분수가 주어졌을 때, 그 합을 기약분수의 형태로 구하는 프로그램을 작성하시오. 기약분수란 더 이상 약분되지 않는 분수를 의미한다.
입력
첫째 줄과 둘째 줄에, 각 분수의 분자와 분모를 뜻하는 두 개의 자연수가 순서대로 주어진다. 입력되는 네 자연수는 모두 30,000 이하이다.
출력
첫째 줄에 구하고자 하는 기약분수의 분자와 분모를 뜻하는 두 개의 자연수를 빈 칸을 사이에 두고 순서대로 출력한다.
✏️문제 풀이
- 두 줄에 걸쳐 분수의 분자와 분모를 입력 :
denom1
,denom2
- 최대공약수를 구하는 함수
gcd()
정의- 유클리드 호제법을 사용
- 최소공배수를 구하는 함수
lcm()
정의 - 두 분모의 최소공배수를 구하여
common_denominator
에 저장- 두 분수를 더할 때 공통 분모가 됨
- 첫 번째 분수의 분자를 새로운 분모에 맞게 조정
- 예: 1/2 + 1/3 에서 1/2의 분자를 3으로 조정 (2*3/2 = 3)
- 두 번째 분수의 분자를 새로운 분모에 맞게 조정
- 예: 1/2 + 1/3 에서 1/3의 분자를 2로 조정 (1*6/3 = 2)
- 조정된 두 분수의 분자를 더함
- 예: 3/6 + 2/6 = 5/6
- 최종 분자와 분모의 최대공약수를 구함 : 기약분수를 구하기 위하여 필요
- 최대공약수로 분자와 분모를 나누어 기약분수 형태로 출력
코드와 함께 보는 풀이
# 두 줄에 걸쳐 분수의 분자와 분모를 입력
denom1 = list(map(int, input().split()))
denom2 = list(map(int, input().split()))
# 최대공약수를 구하는 함수 : 유클리드 호제법을 사용
def gcd(a, b):
while b:
a, b = b, a % b
return a
# 최소공배수를 구하는 함수
def lcm(a, b):
return a * b // gcd(a, b)
# 두 분모의 최소공배수를 구함 : 공통 분모
common_denominator = lcm(denom1[1], denom2[1])
# 첫 번째 분수의 분자를 새로운 분모에 맞게 조정
numerator1 = denom1[0] * (common_denominator // denom1[1])
# 두 번째 분수의 분자를 새로운 분모에 맞게 조정
numerator2 = denom2[0] * (common_denominator // denom2[1])
# 조정된 두 분수의 분자를 더함
total_numerator = numerator1 + numerator2
# 최종 분자와 분모의 최대공약수를 구함
gcd_value = gcd(total_numerator, common_denominator)
# 최대공약수로 분자와 분모를 나누어 기약분수 형태로 출력
print(total_numerator // gcd_value, common_denominator // gcd_value)
💯제출 코드
denom1 = list(map(int, input().split()))
denom2 = list(map(int, input().split()))
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
common_denominator = lcm(denom1[1], denom2[1])
numerator1 = denom1[0] * (common_denominator // denom1[1])
numerator2 = denom2[0] * (common_denominator // denom2[1])
total_numerator = numerator1 + numerator2
gcd_value = gcd(total_numerator, common_denominator)
print(total_numerator // gcd_value, common_denominator // gcd_value)
댓글남기기