怎么在Python中素遞歸算法求最小公倍數和最大公約數?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
Python是一種跨平臺的、具有解釋性、編譯性、互動性和面向對象的腳本語言,其最初的設計是用于編寫自動化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發獨立的項目和大型項目。
具體如下:
# 最小公倍數
def lcm(a, b, c=1):
if a * c % b != 0:
return lcm(a, b, c+1)
else:
return a*c
test_cases = [(4, 8), (35, 42), (5, 7), (20, 10)]
for case in test_cases:
print('lcm of {} & {} is {}'.format(*case, lcm(*case)))
def lcm(a, b):
for i in range(2, min(a,b)+1):
if a % i == 0 and b % i == 0:
return i * lcm(a//i, b//i)
else:
return a*b
test_cases = [(4, 8), (5, 7), (24, 16), (35, 42)]
for case in test_cases:
print('lcm of {} & {} is {}'.format(*case, lcm(*case)))
# 最大公約數
def gcd(a, b):
if a == b:
return a
elif a-b > b:
return gcd(a-b, b)
else:
return gcd(b, a-b)
test_cases = [(35, 14), (88, 66), (5, 4), (20, 10)]
for case in test_cases:
print('GCD of {} & {} is {}'.format(*case, gcd(*case)))運行結果:
lcm of 4 & 8 is 8
lcm of 35 & 42 is 210
lcm of 5 & 7 is 35
lcm of 20 & 10 is 20
GCD of 35 & 14 is 7
GCD of 88 & 66 is 22
GCD of 5 & 4 is 1
GCD of 20 & 10 is 10
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。