Ad

Class for calculation with fractions

def gcd(a, b):
    if a == b:
        return a
    elif a > b:
        if a % b != 0:
            return gcd(b, a % b)
        else:
            return b
    else:
        return gcd(b, a)


def lcm(a, b):
    return a * b // gcd(a, b)

class Fraction:

    def __init__(self, numerator, denominator):
        g = gcd(numerator, denominator)
        self.top = numerator // g
        self.bottom = denominator // g
    
    #Equality test
    
    def __eq__(self, other):
        first_num = self.top * other.bottom
        second_num = other.top * self.bottom
        return first_num == second_num
        
    def __add__(self, other):
        sum_denom = lcm(self.bottom, other.bottom)
        first_num = sum_denom * self.top // self.bottom
        second_num = sum_denom * other.top // other.bottom
        sum_num = first_num + second_num
        return Fraction(sum_num, sum_denom)
    
    def __sub__(self, other):
        dif_denom = lcm(self.bottom, other.bottom)
        first_num = sum_denom * self.top // self.bottom
        second_num = sum_denom * other.top // other.bottom
        dif_num = first_num - second_num
        return Fraction(dif_num, dif_denom)
        
    def __mul__(self, other):
        return Fraction(self.top * other.top, self.bottom * other.bottom)
        
    def __truediv__(self, other):
        return Fraction(self.top * other.bottom, self.bottom * other.top)
    
    def __str__(self):
        return str(self.top) + "/" + str(self.bottom)
Arithmetic
Mathematics
Algorithms
Logic
Numbers
def greatest_common_divisor(*args):

    def gcd(a, b):
        if a == b: return a
        elif a > b:
            return (gcd(b, a % b) if a % b != 0 else b)
        else:
            return gcd(b, a)

    res = gcd(args[0], args[1])
    if len(args) > 2:
        for i in range(2, len(args)):
            res = gcd(res, args[i])
    return res