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
sys.stdout.write("Please enter 2 integer numbers\n")
line = sys.stdin.readline()
ss = string.split(line)
if len(ss) != 2:
sys.stderr.write("Sorry I got %d elements\n" % len(ss))
sys.exit(1)
# Convert the two string to integer numbers.
a = int(ss[0])
b = int(ss[1])
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.