温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Python中素递归算法求最小公倍数和最大公约数

发布时间:2021-05-11 18:17:58 来源:亿速云 阅读:193 作者:Leah 栏目:开发技术

怎么在Python中素递归算法求最小公倍数和最大公约数?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI