Add Fractions Reduced
Python
Hard
3 views
Problem Description
Two fractions are provided as p/q form. Add them and output result in reduced form p/q with q positive.
Input Format
Two lines: f1 then f2.
Output Format
One fraction p/q.
Official Solution
import sys,math
lines=sys.stdin.read().splitlines()
if len(lines)<2:
sys.exit(0)
def parse(fr):
fr=fr.strip()
p,q=fr.split('/')
return int(p),int(q)
p1,q1=parse(lines[0])
p2,q2=parse(lines[1])
num=p1*q2+p2*q1
den=q1*q2
if den<0:
num=-num
den=-den
g=math.gcd(abs(num),abs(den))
num//=g
den//=g
sys.stdout.write(f'{num}/{den}')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!