[Tutor] A better way for greatest common divisor

David Hutto smokefloat at gmail.com
Fri Jul 30 03:47:20 CEST 2010

This is basically to get feedback, on a better way to show the
greatest common divisor in fraction, in order to reduce it fully, than
the one I've come up with. I'm sure there are better ways, so if you
have simpler method, or critique of what I've done, let me know.

'''Greatest Common Divisor Function'''
def gcd(num,den):
    while True:
        '''Find if numerator is less than denominator'''
        if num < den:
            '''Range backwards from larger number'''
            for y in range.__reversed__(range(1,den+1)):
                county = y
                '''If den is evenly divisible by county'''
                if den%county == 0:
                    '''And if num is divisible by county'''
                    if num%county == 0:
                        '''We have funneled the largest number\
                        divisible by both, by looping backwards\
                        from the larger number'''
                        numdiv = num/county
                        dendiv = den/county
                        print('Reduced value is: %d/%d' % (numdiv,dendiv))
        '''Below is about the same, except turns the fraction\
        into it's wholenumber/fraction counterpart'''
        if num > den:
            for x in range.__reversed__(range(1,num+1)):
                countx = x
                if num%countx == 0:
                    if den%countx == 0:
                        numdiv = num/countx
                        dendiv = den/countx
                        print('Reduced value is: %d/%d' % (numdiv,dendiv))


'''Greatest Common Divisor Function Instance'''
num=int(float(input('Input numerator: ')))
den=int(float(input('Input denominator: ')))


More information about the Tutor mailing list