Python求最小公倍數4種方法總結
更新時間:2023年10月28日 11:02:09 作者:旦旦崽
這篇文章主要給大家介紹了關于Python求最小公倍數4種方法的相關資料,最小公倍數不可以像最大公約數那樣直接利用輾轉相除法求出,但可以借助輾轉相除法求得的最大公約數來求最小公倍數,需要的朋友可以參考下
最小公倍數:
兩個或多個整數公有的倍數叫做它們的公倍數,其中除0以外最小的一個公倍數就叫做這幾個整數的最小公倍數。整數a,b的最小公倍數記為[a,b],同樣的,a,b,c的最小公倍數記為[a,b,c],多個整數的最小公倍數也有同樣的記號。
利用Python求最小公倍數(4種方法)
算法一
# 算法1 def least_commo_multiple1(): print("請輸入3個數") x1 = int(input("請輸入x1:")) x2 = int(input("請輸入x2:")) x3 = int(input("請輸入x3:")) x0 = max(x1,x2,x3) i = 1 while(1): j = x0*i if j % x1==0 and j % x2 ==0 and j % 3 ==0: break i+=1 print(x1,x2,x3,"這三個數的最小公倍數是:",j) def max(x,y,z): if x>y and x>z: return x elif y>x and y>z: return y else: return z
算法二
# 算法2 def least_commo_multiple2(): t=1 print("請輸入3個數") x1 = int(input("請輸入x1:")) x = x1 x2 = int(input("請輸入x2:")) y = x2 x3 = int(input("請輸入x3:")) z = x3 x0 = max(x1,x2,x3) for i in range(2,x0+1): flag = 1 while flag: flag = 0 if x1 % i == 0: x1 = x1 / i flag = 1 if x2 % i == 0: x2 = x2 / i flag = 1 if x3 % i == 0: x3 = x3 / i flag = 1 if flag == 1: t = t * i x0 = max(x1,x2,x3) print(x, y, z, "這三個數的最小公倍數是:", t)
算法三
# 算法3 def least_commo_multiple3(): print("請輸入3個數") x1 = int(input("請輸入x1:")) x2 = int(input("請輸入x2:")) x3 = int(input("請輸入x3:")) x0 = x1*x2/most_common_divisor(x1,x2) x0 = x0 * x3 / most_common_divisor(x0, x3) print(x1,x2,x3,"這三個數的最小公倍數是:",x0) def most_common_divisor(a, b): c = a % b while c != 0: a = b b = c c = a % b return b
算法四
# 算法4 def least_commo_multiple4(): print("請輸入3個數") x1 = int(input("請輸入x1:")) x2 = int(input("請輸入x2:")) x3 = int(input("請輸入x3:")) x0 = ff(ff(x1,x2),x3) print(x1, x2, x3, "這三個數的最小公倍數是:", x0) def ff(a,b): a1 = a b1 = b c = a%b while c != 0: a = b b = c c = a%b return a1*b1/b
主函數
# 主函數 if __name__ == "__main__": # least_commo_multiple1() # least_commo_multiple2() # least_commo_multiple3() least_commo_multiple4()
效果截圖:
以上就是Python語言求解三個數的最小公倍數啦~??
總結
到此這篇關于Python求最小公倍數的文章就介紹到這了,更多相關Python求最小公倍數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python Django模板之模板過濾器與自定義模板過濾器示例
這篇文章主要介紹了Python Django模板之模板過濾器與自定義模板過濾器,結合實例形式分析了Django框架模板過濾器與自定義模板過濾器相關功能、原理、使用方法及相關操作注意事項,需要的朋友可以參考下2019-10-10