gcd.py
#!/usr/bin/env python
#
# Get two numbers from user, print their gcd (Greatest Common Divisor).
#
# Author: Yotam Medini [email protected] -- Created: 2005/June/19
#
import sys
import string
# Check for 2 parameters
if len(sys.argv) != 3:
sys.stderr.write("I should be called with 2 parameters!\n")
sys.stderr.write("Usage: %s <number> <number>\n" % sys.argv[0])
sys.exit(1)
# Convert the two command line parameters strings to integer numbers.
a = int(sys.argv[1])
b = int(sys.argv[2])
sys.stdout.write("gcd(%d,%d) = " % (a, b)); # The result will come soon...
# If any is negative, convert it to positive.
# It does not change the gcd(a,b) result !!
if a < 0:
a = -a
if b < 0:
b = -b
# Let's always have a >= b
if a < b:
# swap a <-> b
temp = a
a = b
b = temp
if a == 0:
# Since a >= b >= 0, we must have b == 0.
# Any non-zero integer divides 0, and so:
sys.stdout.write("Infinity\n")
else:
# Now the beautiful Euclid algorithm. Short and smart.
while b != 0:
residue = a % b
a = b
b = residue
sys.stdout.write("%d\n" % a)
sys.exit(0)
Generated by GNU enscript 1.6.4.