Reduce Fraction
Python
Medium
2 views
Problem Description
Input has two integers p and q are provided (q != 0). Reduce the fraction p/q and output as p q (reduced). Keep denominator positive.
Input Format
One line: p q.
Output Format
One line: rp rq.
Constraints
q != 0, values fit in 64-bit.
Official Solution
import sys,math
p=sys.stdin.read().strip().split()
if len(p)<2: sys.exit(0)
a=int(p[0]); b=int(p[1])
g=math.gcd(abs(a),abs(b))
a//=g; b//=g
if b<0:
a=-a; b=-b
sys.stdout.write(f'{a} {b}')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!