最大公约数
实现方法1:迭代取余
n_1=input('please enter an int:')
n_2=input('please enter another int:')
def mcd(x,y):#Maximum common divisor
if x < y:
m=y
y=x
x=m
z_1=x%y
while z_1!=0:
x=y
y=z_1
z_1=x%y
return y
num_1=int(n_1)
num_2=int(n_2)
final=mcd(num_1,num_2)
print(final)
实现方法2:暴力检索
def mcd(x,y):
if x<y:
m=y
y=x
x=m
for i in range(1,y+1):
if (x%i==0)and (y%i==0):
final=i
return final
n_1=input('please enter an int:')
n_2=input('please enter another int:')
num_1=int(n_1)
num_2=int(n_2)
final=mcd(num_1,num_2)
print(final)
最小公倍数
暴力检索:
def lcmu(x, y):#define function :Least common multiple
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# 获取用户输入
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))
print( num1,"和", num2,"的最小公倍数为", lcmu(num1, num2))
两数乘积除以最大公约数:
import math
def lcmu(x,y):
mcd=math.gcd(x,y)
lcm=x*y/mcd
return lcm
# 获取用户输入
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))
print( num1,"和", num2,"的最小公倍数为", lcmu(num1, num2))