python 最小公倍数
最小公倍数
求解两个整数(不能是负数)的最小公倍数
方法一:穷举法
1 def LCM(m, n): 2 3 if m*n == 0: 4 return 0 5 if m > n: 6 lcm = m 7 else: 8 lcm = n 9 10 while lcm%m or lcm%n: 11 lcm += 1 12 13 return lcm
方式二:公式lcm = a*b/gcd(a, b)
1 def gcd(m,n): 2 3 if not n: 4 return m 5 else: 6 return gcd(n, m%n) 7 8 def LCM(m, n): 9 10 if m*n == 0: 11 return 0 12 return int(m*n/gcd(m, n)) 13 14 if __name__ == '__main__': 15 a = int(input('Please input the first integers : ')) 16 b = int(input('Please input the second integers : ')) 17 result = LCM(a, b) 18 print('lcm = ', result)