Jacob
Jacob

Reputation: 1

I want to find the difference between two fraction numbers

I want to find the difference between two fraction numbers.

I created a port of code but somehow it doesn't give right output and I don't know where is the problem

def findGCD(a,b):
    while b>0:
        r=a%b
        a=b
        b=r
    return a

def min_frac(num1,den1,num2,den2):
    den = den1 * den2
    num = num1*den2 + den1*num2
    gcd = findGCD(den,num)
    if gcd != 1:
        den *= gcd
        num *= gcd

Upvotes: 0

Views: 57

Answers (1)

user7864386
user7864386

Reputation:

(1) Since you want to find the difference, num1*den2 + den1*num2 should be num1*den2 - den1*num2.

(2) You need to divide both den and num by gcd, not multiply.

(3) You need to return num and den, otherwise you don't see the output.

def min_frac(num1,den1,num2,den2):
    den = den1 * den2
    num = num1*den2 - den1*num2
    gcd = findGCD(den,num)
    if gcd != 1:
        den /= gcd
        num /= gcd
    return num, den

Upvotes: 2

Related Questions