欧几里得算法(辗转相除法)-- 实现分数计算

博客地址:https://www.cnblogs.com/zylyehuo/

# -*- coding: utf-8 -*-
"""
利用欧几里得算法实现一个分数类,支持分数的四则运算(加法)
"""


class Fraction:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        x = self.gcd(a, b)
        self.a /= x
        self.b /= x

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

    # 最小公倍数
    def zgs(self, a, b):
        # 12 16 -> 4
        # 3*4*4=48
        x = self.gcd(a, b)
        return a * b / x

    # 加法
    def __add__(self, other):
        a = self.a
        b = self.b
        c = other.a
        d = other.b
        fenmu = self.zgs(b, d)
        fenzi = a * fenmu / b + c * fenmu / d
        return Fraction(fenzi, fenmu)

    def __str__(self):
        return "%d/%d" % (self.a, self.b)


a = Fraction(1, 3)
b = Fraction(1, 2)
print(a + b)

posted @ 2023-08-19 23:38  zylyehuo  阅读(13)  评论(0编辑  收藏  举报