Python基于递归算法求最小公倍数和最大公约数示例

yipeiwu_com5年前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

PS:这里再为大家推荐一款本站相关在线工具供大家参考:

在线最小公倍数/最大公约数计算工具:
http://tools.jb51.net/jisuanqi/gbs_gys_calc

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python求离散序列导数的示例

Python求离散序列导数的示例

有一组4096长度的数据,需要找到一阶导数从正到负的点,和三阶导数从负到正的点,截取了一小段。 394.0 388.0 389.0 388.0 388.0 392.0 39...

python 将字符串中的数字相加求和的实现

python 将字符串中的数字相加求和的实现

计算字符串中所有数字的和,字符串中有数字和字母组合而成 如果出现连续数字,按照一个数操作 具体解释在代码行里: def sum_str(str1): len1=len(str...

将Python文件打包成.EXE可执行文件的方法

利用Python写了一个小脚本想要传给使用Windows但没有装Python的朋友执行,这时候就可以利用将档案包装成exe档案,让没有Python的朋友也可以执行。本篇将介绍利用套件...

windows环境下tensorflow安装过程详解

windows环境下tensorflow安装过程详解

一、前言 本次安装tensorflow是基于Python的,安装Python的过程不做说明(既然决定按,Python肯定要先了解啊):本次教程是windows下Anaconda安装Ten...

Python获取本机所有网卡ip,掩码和广播地址实例代码

本文主要研究的是使用Python获取本机所有网卡ip,掩码和广播地址,分享了相关的实例代码,具体介绍如下。 搜了一天,竟然没找到一段合适的代码来获取机器中所有网卡的ip,掩码和广播地址,...