最小公倍数 (LCM) - Python
Least Common Multiple (LCM) - Python
这不是关于我如何做的,更多的是关于这种方法有什么问题。我设法使用其他方法解决了这个问题,但我不知道为什么我不能用这个方法。我在这里错过了什么?
示例输入:4,6
预期输出:12
实际输出:4
n1, n2 = map(int, input("n1 and n2: ").split(','))
def lcmCalc (n1,n2):
i = 2
lcm = 1
while (n1 != 1) and (n2 != 1):
if n1 % i == 0 and n2 % i == 0:
lcm *= i
n1 = n1/i
n2 = n2/i
elif n1 % i != 0 and n2 % i == 0:
lcm *= i
n2 = n2/i
elif n1 % i == 0 and n2 % i != 0:
lcm *= i
n1 = n1/i
else:
i += 1
return lcm
print(lcmCalc(n1,n2))
我很想使用关系 :
lcm(a,b) = |a.b| / gcd(a,b)
当然还有 gcd(a,b) = gcd(b, a%b) & gcd(a,0) = a
所以我的代码:
def gcd(a,b):
if b ==0:
return a
else:
return gcd(b, a % b)
def lcm(a,b):
return int(abs(a*b) / gcd(a,b))
或者 - 如果您不反对标准库的一点帮助:
from math import gcd
def lcm(a,b):
return int(abs(a*b) / gcd(a,b))
你很接近。以下是编辑内容:
def lcmCalc(n1, n2):
i = 2
lcm = 1
while (n1 != 1) and (n2 != 1):
if n1 % i == 0 and n2 % i == 0:
lcm *= i
n1 = n1 // i # <== use floor division operator
n2 = n2 // i
elif n2 % i == 0: # <== remove unneeded 2nd test
lcm *= i
n2 = n2 // i
elif n1 % i == 0: # <== remove unneeded 2nd test
lcm *= i
n1 = n1 // i
else:
i += 1
return lcm * n1 * n2 # <== need to include residuals
当外层循环终止时,n1或n2中的任何一个可能仍在1
之上。该残差需要包含在结果中。
这不是关于我如何做的,更多的是关于这种方法有什么问题。我设法使用其他方法解决了这个问题,但我不知道为什么我不能用这个方法。我在这里错过了什么?
示例输入:4,6 预期输出:12 实际输出:4
n1, n2 = map(int, input("n1 and n2: ").split(','))
def lcmCalc (n1,n2):
i = 2
lcm = 1
while (n1 != 1) and (n2 != 1):
if n1 % i == 0 and n2 % i == 0:
lcm *= i
n1 = n1/i
n2 = n2/i
elif n1 % i != 0 and n2 % i == 0:
lcm *= i
n2 = n2/i
elif n1 % i == 0 and n2 % i != 0:
lcm *= i
n1 = n1/i
else:
i += 1
return lcm
print(lcmCalc(n1,n2))
我很想使用关系 :
lcm(a,b) = |a.b| / gcd(a,b)
当然还有 gcd(a,b) = gcd(b, a%b) & gcd(a,0) = a
所以我的代码:
def gcd(a,b):
if b ==0:
return a
else:
return gcd(b, a % b)
def lcm(a,b):
return int(abs(a*b) / gcd(a,b))
或者 - 如果您不反对标准库的一点帮助:
from math import gcd
def lcm(a,b):
return int(abs(a*b) / gcd(a,b))
你很接近。以下是编辑内容:
def lcmCalc(n1, n2):
i = 2
lcm = 1
while (n1 != 1) and (n2 != 1):
if n1 % i == 0 and n2 % i == 0:
lcm *= i
n1 = n1 // i # <== use floor division operator
n2 = n2 // i
elif n2 % i == 0: # <== remove unneeded 2nd test
lcm *= i
n2 = n2 // i
elif n1 % i == 0: # <== remove unneeded 2nd test
lcm *= i
n1 = n1 // i
else:
i += 1
return lcm * n1 * n2 # <== need to include residuals
当外层循环终止时,n1或n2中的任何一个可能仍在1
之上。该残差需要包含在结果中。