Sum of fractions#7363

Sum of fractions (Editorial)

It's obvious that {a \over b} + {c \over d} = {ad + bc \over bd}. We need to simplify the resulting fraction by their greatest common divisor.

Algorithm implementation

The gcd function returns the greatest common divisor of the numbers and .

int gcd(int a, int b)
{
  return (!b) ? a : gcd(b,a % b);
}

The main part of the program. Read the input data.

scanf("%d %d %d %d",&a,&b,&c,&d);

Compute the resulting fraction .

p = a * d + c * b;
q = b * d;

Compute the GCD of the numerator and denominator. Simplify the fraction.

g = gcd(p,q);
p /= g; q /= g;

Print the answer. If the answer is an integer (denominator equals ), then print only the numerator.

if (q == 1) printf("%d\n",p);
else printf("%d %d\n",p,q);

Python implementation

Read the input data.

a, b, c, d = map(int, input().split())

Compute the resulting fraction .

p = a * d + c * b
q = b * d

Compute the GCD of the numerator and denominator. Simplify the fraction.

g = math.gcd(p, q)
p //= g
q //= g

Print the answer. If the answer is an integer (denominator equals ), then print only the numerator.

if q == 1: print(p)
else: print(p, q)