欧几里得算法python

一、问题描述

求最大公约数

python 复制代码
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):
        x = self.gcd(a, b)
        return a / x * b

    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)

二、结果展示

python 复制代码
5/6
相关推荐
用户25191624271110 小时前
Python之语言特点
python
刘立军10 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机14 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机15 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i16 小时前
django中的FBV 和 CBV
python·django
c8i16 小时前
python中的闭包和装饰器
python
这里有鱼汤19 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩1 天前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP2 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python