Monday, April 12, 2010

Python - Finding GCD with Euclids Algorithm

# Implementing the Euclidean Algorithm
# is simple in python.
#
# Euclid's algorithm is used to efficiently
# find two numbers greatest common divisor (GCD)
 
# Division based Euclidean algorithm
def gcd(a,b):
    while b != 0:
        temp = b
        b = a%b
        a = temp
    return a
 
# Recursive based Euclidean algorithm
def recursiveGCD(a,b):
    if b==0:
        return a
    else:
        return recursiveGCD(b, a%b)
 
 
# just to prove they both work the same:
def findGCD(a,b):
    divisionStyle = gcd(a,b)
    recursiveStyle = recursiveGCD(a,b)
    if divisionStyle != recursiveStyle:
        return "Fail...GCDs differ"
    else:
        return divisionStyle
 
print findGCD(1071, 462)
print findGCD(5, 10)
print findGCD(5214, 24324)
 
# my output:
#   21
#   5
#   6
 
 
 

No comments:

Post a Comment