带负数的Python gcd

时间:2013-07-29 16:29:16

标签: python python-3.x

我正在编写自己的Rational类版本,我希望递归地使用最大的公约数。我需要考虑负数 - 我总是想在分子中表示我的负数,但是让我们说num = 1和denom = -2,我想把它表示为num = -1和denom = 2并且如果num = -1且denom = -2则num = 1且denom = 2。我知道我需要使用abs函数来找到gcd,但是如果我删除负号以找到gcd我需要把它放回去......这就是我到目前为止所拥有的......

def gcd(a,b):

    '''Greatest common divisor function
    (a and b are integers)'''
    if b==0:
        return a
    else:
        return gcd(b,a%b)

class Rational:

    def __init__(self,a=0,b=1):

        '''Constructor for Rational'''
        if b==0:
            return 'Denominator cannot be zero.'
        else:
            g=gcd(abs((a,b))
            self.n=a/g       
            self.d=b/g
            # I need to 'undo' the abs to get my self.n and self.d- 
                if that makes sense!!

1 个答案:

答案 0 :(得分:2)

你可以做到

self.n = abs(a/g)
self.m = abs(b/g)
if a*b < 0:  # i.e. signs are different 
    self.n = -self.n
相关问题