Skip to main content
 首页 » 编程设计

python之能被1到20的所有数整除的最小正数

2025年05月04日12dudu

我的代码有什么问题?当我运行程序时,没有打印任何内容。我想打印能被 1 到 20 的所有数字整除的最小数字。

found = False 
i = 20 
while found==False: 
    c = 0    # c checks if the number is the one im looking for 
    for x in range(1,21): 
        if i%x==0: 
            c = c + 1 
    if c==20: # if c = 20 then its the number im looking for 
        print i 
        found = True 
    i = i + 1     

请您参考如下方法:

蛮力:

from itertools import count 
for i in count(20): 
    if all(map(lambda x: i % x == 0, range(1, 21))): 
        print i 
        break 

非暴力破解:

from itertools import count, takewhile 
 
def primes(n): 
    "Generate prime numbers up to n" 
    seen = list() 
    for i in xrange(2, n + 1): 
        if all(map(lambda prime: i % prime, seen)): 
            seen.append(i) 
            yield i 
 
def smallest(n): 
    result = 1 
    for prime in primes(n): 
        bprime = max(takewhile(lambda x:x<=n, (prime ** c for c in count(1)))) 
        # we could just take last instead of max() 
        result *= bprime 
    return result 
 
print smallest(20)