Skip to main content
 首页 » 编程设计

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

2024年12月31日8xing901022

我想创建一个函数,它生成一个列表,其中包含从 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]