計算一組數的最大公約數和最小公倍數-python
阿新 • • 發佈:2018-11-03
直接上程式碼了,實現很簡單,有更好的辦法希望可以交流 (每個函式可以輸入多個引數,我是以3個為例)。
def hcf(*x): #計算最大公約數 smaller=min(x) for i in reversed(range(1,smaller+1)): if list(filter(lambda j: j%i!=0,x)) == []: return i def lcm(*x): #計算最小公倍數 greater=max(x) while True: if list(filter(lambda i: greater%i!=0,x)) == []: return greater greater+=1 num1=int(input("輸入第一個數字: ")) num2=int(input("輸入第二個數字: ")) num3=int(input("輸入第三個數字: ")) print( num1,"、", num2,"和", num3,"的最大公約數為:", hcf(num1, num2, num3)) print( num1,"、", num2,"和", num3,"的最小公倍數為:", lcm(num1, num2, num3))
輸入第一個數字: 2
輸入第二個數字: 4
輸入第三個數字: 8
2 、 4 和 8 的最大公約數為: 2
2 、 4 和 8 的最小公倍數為: 8