Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-226

Add Fractions

Problem

Add the fractions num1/den1 and num2/den2 and return the reduced result as [numerator, denominator] with a positive denominator.

Cross-multiply to add, then divide both parts by their greatest common divisor. A zero result is written as [0, 1].

Hint

gcd(0, x) is x, so the same reduction code handles a zero numerator.

Test cases

case 1
in: [1,2,1,3]
expected: [5,6]
case 2
in: [1,4,1,4]
expected: [1,2]
case 3
in: [1,2,1,2]
expected: [1,1]
case 4
in: [0,5,1,5]
expected: [1,5]
case 5
in: [1,6,-1,6]
expected: [0,1]
Starter codePython
def add_fractions(num1, den1, num2, den2):
    # Your code here
    pass

5 test cases · run your code against them in the editor