
在化学式中无机物里,一般的情况下都表示的是各种元素的原子个数比,而知道化合价后,根据化合物中元素化合价的正负代数和为零,所以需要求出最小公倍数从而确定原子个数比的。最小公倍数可用于解决一些问题,因此要关注最小公倍数。在python中怎么求去最小公倍数呢?下面,小编来教教你吧。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <p style= "line-height: normal;" ># 最小公倍数
def lcm(a, b, c=1):
if a * c % b != 0:
return lcm(a, b, c+1)
else :
return a*c
test_cases = [(4, 8), (35, 42), (5, 7), (20, 10)]
for case in test_cases:
print ( 'lcm of {} & {} is {}' .format(* case , lcm(* case ))) <br></p>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <p style= "line-height: normal;" >def lcm(a, b):
for i in range(2, min(a,b)+1):
if a % i == 0 and b % i == 0:
return i * lcm(a
else :
return a*b
test_cases = [(4, 8), (5, 7), (24, 16), (35, 42)]
for case in test_cases:
print ( 'lcm of {} & {} is {}' .format(* case , lcm(* case )))<br></p>
|
以上就是python中求取最小公倍数的方法,最小公倍数虽然在平时我们感到不到它的存在,但是他的作用很大,它为什么计算提供了基础,快套下上串代码求最小公倍数试试看吧~
(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)