Search This Blog

Wednesday, May 1, 2019

Python Euclid's Algorithm

I was tripping through Wikipedia, as one does, and ran into Euclid's Algorithm in https://en.wikipedia.org/wiki/Euclidean_algorithm, and thought to myself...

# Euclid's Algorithm for finding the greatest # common denominator of two numbers. def gdc(a, b):
# Setup a = abs(a) b = abs(b) # Work while (b!=0): t=a a=b b=t%b # Fin return a # test cases print(gdc(60, 96)) # should be 12 print(gdc(20, 8)) # should be 4 print(gdc(3009, 884)) # should be 17 print(gdc(40902, 24140)) # should be 34 print(gdc(14157, 5950)) # should be 1 print(gdc(10, 0)) # should be 10 print(gdc(0, 10)) # should be 10 print(gdc(4, 10)) # should be 2 print(gdc(10, 4)) # should be 2 print(gdc(-10, 4)) # should be 2 print(gdc(10, -4)) # should be 2 / without abs() this is -2 print(gdc(24, 18)) # should be 6 print(gdc(3, 24)) # should be 3