python實現求最大公約數與最小公倍數


 

  記錄python實現最大公約數&最小公位數兩種算法

 

概念

最大公約數:指兩個或多個整數共有約數中最大的一個

最小公倍數:兩個或多個整數公有的倍數叫做它們的公倍數,其中除0以外最小的一個公倍數就叫做這幾個整數的最小公倍數

二者關系:兩個數之積=最小公倍數*最大公約數

 

實例

輾轉相除法

 

a=int(input('please enter 1st num:'))
b=int(input('please enter 2nd num:'))
s=a*b
while a%b!=0:
    a,b=b,(a%b)   
else:
    print(b,'is the maximum common divisor')
    print(s//b,'is the least common multiple')

#運行結果
please enter 1st num:10
please enter 2nd num:15
5 is the Maximum common divisor
30 is the Least common multiple

 

 

更相減損法

a=int(input('please enter 1st num:'))
b=int(input('please enter 2nd num:'))
s=a*b
    
while a!=b:
    if a>b:
        a-=b
    elif a<b:
        b-=a
else:
    print(a,'is the maximum common divisor')
    print(s//a,'is the least common multiple')

#運行結果
please enter 1st num:40
please enter 2nd num:60
20 is the maximum common divisor
120 is the least common multiple

  

輾轉相除法與更相減損術的區別

(1)都是求最大公因數的方法,計算上輾轉相除法以除法為主,更相減損術以減法為主,計算次數上輾轉相除法計算次數相對較少,特別當兩個數字大小區別較大時計算次數的區別較明顯。
(2)從結果體現形式來看,輾轉相除法體現結果是以相除余數為0則得到,而更相減損術則以減數與差相等而得到。

 


免責聲明!

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



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