计算最小公倍数

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在数学中,最小公倍数(Least Common Multiple,LCM)是能被两个或多个数整除且没有余数的最小正整数。例如,4 和 6 的最小公倍数是 12,因为 12 是能同时被 4 和 6 整除的最小数。

最小公倍数

编写一个函数 lcm(numbers),它接受一个数字列表作为参数,并返回它们的最小公倍数。你的函数应该使用以下公式来计算两个数字 xy 的最小公倍数:lcm(x, y) = x * y / gcd(x, y),其中 gcd(x, y)xy 的最大公约数。

要解决这个问题,你可以使用 functools.reduce() 函数将 lcm() 公式应用于列表中的所有数字。你也可以使用 math.gcd() 函数来计算两个数字的最大公约数。

from functools import reduce
from math import gcd

def lcm(numbers):
  return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers)
lcm([12, 7]) ## 84
lcm([1, 3, 4, 5]) ## 60

总结

在这个挑战中,你已经学会了如何使用 functools.reduce()math.gcd() 函数来计算数字列表的最小公倍数。lcm() 函数使用 lcm(x, y) = x * y / gcd(x, y) 公式来计算两个数字的最小公倍数。