Skip to main content
 首页 » 编程设计

python之优化代码以找到可被 1-20 之间的所有整数整除的最小数字

2025年05月04日8zhenyulu

我目前正在尝试解决“能被 1 到 20 的所有数字整除的最小正数是多少?”这个问题

到目前为止,我已经编写了一些似乎有效但需要很长时间的代码。此外,我不得不在 if 中使用大量的“和”语句,这看起来既不高效也不专业。

我可以做些什么来优化这段代码并使其更整洁?

number = 1 
result = 0 
 
def divide(candidate): 
    if candidate % 2 == 0 and candidate % 3 == 0 and candidate % 4 == 0 and candidate % 5 == 0 and candidate % 6 == 0 and candidate % 7 == 0 and candidate % 8 == 0 and candidate % 9 == 0 and candidate % 10 == 0 and candidate % 11 == 0 and candidate % 12 == 0 and candidate % 13 == 0 and candidate % 14 == 0 and candidate % 15 == 0 and candidate % 16 == 0 and candidate % 17 == 0 and candidate % 18 == 0 and candidate % 19 == 0 and candidate % 20 == 0: 
        global result 
        result = 1 
        return 1 
 
    else: 
       global number 
        result = 0 
        number = number + 1 
        return 0 
 
while result == 0: 
divide(number) 
 
print "The lowest number divisible by all integers between 1-20 is:", number 

澄清一下,这不是家庭作业,我正在自学 Python 并尝试解决一些 ProjectEuler 问题。

请您参考如下方法:

您的问题可以在没有计算机帮助的情况下轻松解决,因此优化版本只会打印答案。很难说出您认为可接受的优化量。

下面是如何在没有计算机的情况下解决这个问题。可被 1 到 20 的所有数字整除的最小数字必须能被这些数字中出现的所有质数幂整除。并且,另一方面,如果我们有一个数可以被这个范围内的所有素数幂整除,那么它将被 1 到 20 之间的所有数字整除。由于具有不同底数的素数幂是互质的,所有最高素数幂的乘积对于此范围内的每个质数,都将是答案。所以这是优化后的代码:

print 2**4 * 3**2 * 5 * 7 * 11 * 13 * 17 * 19