国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python基于遞歸算法求最小公倍數(shù)和最大公約數(shù)示例

2020-02-15 22:34:11
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Python基于遞歸算法求最小公倍數(shù)和最大公約數(shù)。分享給大家供大家參考,具體如下:

# 最小公倍數(shù)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)))# 最大公約數(shù)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)))

運(yùn)行結(jié)果:

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:這里再為大家推薦一款本站相關(guān)在線工具供大家參考:

在線最小公倍數(shù)/最大公約數(shù)計(jì)算工具:
http://tools.jb51.net/jisuanqi/gbs_gys_calc

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 关岭| 余姚市| 汝南县| 天门市| 汉川市| 临汾市| 石景山区| 康保县| 克拉玛依市| 黔江区| 滕州市| 易门县| 青浦区| 恩施市| 榕江县| 酒泉市| 施甸县| 桐柏县| 通河县| 厦门市| 永济市| 交城县| 广南县| 余姚市| 西吉县| 嘉祥县| 贺兰县| 南城县| 怀仁县| 当阳市| 衡阳市| 高阳县| 赤城县| 遵义市| 宜川县| 扶风县| 自治县| 平阴县| 南平市| 上蔡县| 汝城县|