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
View Code

 方式二:公式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)
View Code

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM