Skip to content

Instantly share code, notes, and snippets.

@MichaelAquilina
Last active August 29, 2015 14:02
Show Gist options
  • Save MichaelAquilina/bd8d86408ca4653063b7 to your computer and use it in GitHub Desktop.
Save MichaelAquilina/bd8d86408ca4653063b7 to your computer and use it in GitHub Desktop.
Greatest Common Divisor (Python)
#! /usr/bin/python
# Greatest Common Divisor in python
# recursive (as given)
def gcd_r(a, b):
if b == 0:
return a
return gcd(b, a % b)
# iterative: more efficient
# This is due to not requiring to traverse the stack and the better
# use of the cpu cache in a loop (although for such a small code
# snippet this difference can be minimal)
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
if __name__ == '__main__':
# Testing input values
assert gcd(5, 3) == gcd(3, 5) == 1
assert gcd(10, 5) == gcd(5, 10) == 5
assert gcd(1, 0) == gcd(0, 1) == 1
assert gcd(10, 7) == gcd(7, 10) == 1
assert gcd(8, 12) == gcd(12, 8) == 4
assert gcd(21, 15) == gcd(15, 21) == 3
assert gcd(27, 27) == 27
assert gcd(10, 24) == 2
assert gcd(1000, 80) == 40
assert gcd(10000000, 86) == 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment