一、模块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 152. 方法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 172. 方法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
本文介绍了一种使用Python编写的最大公约数计算方法,并通过两种不同的导入方式实现了该功能。第一种方法是从GCDFunction模块导入gcd函数,第二种方法则是直接导入整个模块。此外,还演示了如何循环三次进行最大公约数的计算。

被折叠的 条评论
为什么被折叠?



