python中最小公倍数怎么求

在化学无机化合物中,一般表示各种元素的原子数比。了解化合物价格后,根据化合物中元素化合物的正负代数为零,需要最小公倍数来确定原子数比。最小公倍数可以用来解决一些问题,所以要注意最小公倍数。如何在python中获得最小公倍数?下面,小边来教你。
代码:
# 最小公倍数 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)))
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//i, b//i) 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)))
以上是Python中获得最小公倍数的方法。虽然我们平时感觉不到最小公倍数的存在,但它起着很大的作用。为什么它的计算提供了基础?试试~
(推荐操作系统:windows7系统Python 3.9.1,DELL G3电脑。)
