一、模块GCDFunction.py,用来求两个数的最大公约数
def gcd(n1,n2):
gcd=1
k=2
while k<=n1 and k<=n2:
if n1%k==0 and n2%k==0:
gcd=k
k+=1
return gcd
print "Finishing calculating greatest common divisor"
二、下面,运用模块GCDFunction.py,实现功能:输入两个整数,求它们的最大公约数
1. 方法1:从模块GCDFunction.py导入函数gcd
from GCDFunction import gcd # Import the module
# Prompt the user to enter two integers
n1 = eval(input("Enter the first integer: "))
n2 = eval(input("Enter the second integer: "))
print("The greatest common divisor for", n1,
"and", n2, "is", gcd(n1, n2))
结果为:
Finishing calculating greatest common divisor
enter the first number: 45
enter the second number: 75
the divisor for 45 and 75 is 15
2. 方法2:直接导入模块GCDFunction.py
import GCDFunction
n1 = eval(raw_input("enter the first number: "))
n2 = eval(raw_input("enter the second number: "))
n1n2gcd = GCDFunction.gcd(n1,n2)
print "the divisor for %i and %i is %i" %(n1,n2,n1n2gcd)
结果为:
Finishing calculating greatest common divisor
enter the first number: 45
enter the second number: 75
the divisor for 45 and 75 is 15
三、下面,运用模块GCDFunction.py,实现功能:输入两个整数,求它们的最大公约数,循环做3次
1. 方法1:从模块GCDFunction.py导入函数gcd
from GCDFunction import gcd
for i in range(3):
n1 = eval(raw_input("enter the first number: "))
n2 = eval(raw_input("enter the second number: "))
print "the divisor for %i and %i is %i" %(n1,n2,gcd(n1,n2))
print
结果为:
Finishing calculating greatest common divisor
enter the first number: 15
enter the second number: 75
the divisor for 15 and 75 is 15
enter the first number: 16
enter the second number: 48
the divisor for 16 and 48 is 16
enter the first number: 17
enter the second number: 51
the divisor for 17 and 51 is 17
2. 方法2:直接导入 模块GCDFunction.py
import GCDFunction
for i in range(3):
n1 = eval(raw_input("enter the first number: "))
n2 = eval(raw_input("enter the second number: "))
n1n2gcd = GCDFunction.gcd(n1,n2)
print "the divisor for %i and %i is %i" %(n1,n2,n1n2gcd)
print
结果为:
Finishing calculating greatest common divisor
enter the first number: 15
enter the second number: 75
the divisor for 15 and 75 is 15
enter the first number: 16
enter the second number: 48
the divisor for 16 and 48 is 16
enter the first number: 17
enter the second number: 51
the divisor for 17 and 51 is 17