本文實例講述了Python基于遞歸算法求最小公倍數和最大公約數。分享給大家供大家參考,具體如下:
# 最小公倍數def lcm(a, b, c=1): if a * c % b != 0: return lcm(a, b, c+1) else: return a*ctest_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*btest_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
PS:這里再為大家推薦一款本站相關在線工具供大家參考:
在線最小公倍數/最大公約數計算工具:
http://tools.jb51.net/jisuanqi/gbs_gys_calc
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答