gpt4 book ai didi

python - 返回范围内一组数字的所有最小公倍数

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:04 25 4
gpt4 key购买 nike

我想创建一个函数,它生成一个列表,其中包含从 1 到 300 的所有数字,这些数字可以通过列表理解被 6 和 10 整除。预期输出如下:

 ist_result = special_nums()
list_result
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]

我认为我可能必须以某种方式使用范围函数,但我不确定。有什么想法吗?

最佳答案

来自 here , 定义一个函数来计算 2 个或更多数字的素数:

def gcd(a, b):
"""Return greatest common divisor using Euclid's Algorithm."""
while b:
a, b = b, a % b
return a

def lcm(a, b):
"""Return lowest common multiple."""
return a * b // gcd(a, b)

def lcmm(*args):
"""Return lcm of args."""
return reduce(lcm, args)

接下来,计算数字的 lcm,然后迭代地发出数字。好消息是,如果您知道 lcm,就不必检查范围内的每个数字。

from math import ceil

def get_multiples(start, end, *args):
lcm = lcmm(*args)
start = max(lcm, lcm * ceil(start / lcm)) # max(..., ...) in case start < lcm
for i in range(start, end + 1, lcm):
yield i

>>> list(get_multiples(1, 300, 6, 10))
[30, 60, 90, 120, 150, 180, 210, 240, 270, 300]

如上所述,这是有效的,因为它不会遍历提供范围内的每个值,并且有效地扩展到 > 2 个值:

>>> list(get_multiples(79, 400, 6, 10, 20))
[120, 180, 240, 300, 360]

关于python - 返回范围内一组数字的所有最小公倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com