Search code examples
pythonfunctionfractions

Simplify fraction function does not work properly in Python


i've made an simplifying function and it works fine, but not perfect.

def gcd(a, b):

    while b > 0:
        if a == 0:
            return b
        a, b = b, (a % b)

def add_frac(n1, d1, n2, d2):

    g = gcd(d1, d2)
    
    frac = (((n1 * d2) + (n2 * d1)) // g, (d1 * d2) // g)
    return frac

when I try: print(add_frac(1, 2, 1, 6))it returns (4, 6). I want it to be (2, 3). Any help to get this result? Note! I would like to get the result without using import math

Example that works: print(add_frac(1, 2, 1, 4)) gives (3, 4)


Solution

  • Using your methodology, just find the GCD of the resulting numerator and denominator and divide by that

    def add_frac(n1, d1, n2, d2):
        num = (n1*d2 + n2*d1)
        den = d1*d2
        g = gcd(num,den)
        return num/g, den/g