user2553807
user2553807

Reputation: 329

Python gcd with negative numbers

I'm writing my own version of the Rational class and I want to use the greatest common divisor recursively. I need to take into account negative numbers though- I always want to represent my negative number in the numerator though so let's say num=1 and denom=-2, I would want to represent that as num=-1 and denom=2 and if num=-1 and denom=-2 then num=1 and denom=2. I know I'll need to use the abs function to find the gcd but if I remove the negative sign to find the gcd I need to put it back in... this is what I have so far...

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!!

Upvotes: 1

Views: 2496

Answers (1)

arshajii
arshajii

Reputation: 129537

You can just do

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

Upvotes: 2

Related Questions