Fraction Add

Fraction Add

Medium Programming Interview OOP 25 views
Explanation Complexity

Problem Statement

You get {x}. Create Fraction class that reduces and supports add. Output result as p q reduced.

Input Format

One line: a b c d.

Output Format

One line: p q.

Example

1 6 1 3
1 2

Constraints

b,d != 0.

Input / Output Format

Input Format
One line: a b c d.
Output Format
One line: p q.
Constraints
b,d != 0.

Examples

Input:
1 6 1 3
Output:
1 2

Example Solution (Public)

Programming Interview
import sys,math
p=sys.stdin.read().strip().split()
if len(p)<4: sys.exit(0)
a=int(p[0]); b=int(p[1]); c=int(p[2]); d=int(p[3])
class Fraction:
  def __init__(self,p,q):
    if q<0:
      p=-p
      q=-q
    g=math.gcd(abs(p),abs(q))
    self.p=p//g
    self.q=q//g
  def add(self,other):
    return Fraction(self.p*other.q + other.p*self.q, self.q*other.q)
f1=Fraction(a,b)
f2=Fraction(c,d)
f3=f1.add(f2)
print(f'{f3.p} {f3.q}')

Official Solution Code

import sys,math
p=sys.stdin.read().strip().split()
if len(p)<4: sys.exit(0)
a=int(p[0]); b=int(p[1]); c=int(p[2]); d=int(p[3])
class Fraction:
  def __init__(self,p,q):
    if q<0:
      p=-p
      q=-q
    g=math.gcd(abs(p),abs(q))
    self.p=p//g
    self.q=q//g
  def add(self,other):
    return Fraction(self.p*other.q + other.p*self.q, self.q*other.q)
f1=Fraction(a,b)
f2=Fraction(c,d)
f3=f1.add(f2)
print(f'{f3.p} {f3.q}')
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.