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

c3n*_*ury 1 python math divide

我目前正试图解决问题"从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
Run Code Online (Sandbox Code Playgroud)

只是为了澄清,这不是家庭作业,我自己教自己Python,并尝试一些ProjectEuler问题作为其中的一部分.

Sve*_*ach 9

没有计算机的帮助,您的问题可以轻松解决,因此优化版本只需打印答案即可.要告知可以接受的优化程度有点难以理解.

这是如何在没有计算机的情况下解决这个问题.从1到20的所有数字可被整除的最小数字必须能够被这些数字中出现的所有主要幂所整除.而且,另一方面,如果我们有一个可被这个范围内的所有主要权力整除的数字,它将被所有数字从1到20分解.因为具有不同基数的主权是互质的,所有最高权力的乘积对于这个范围内的每个素数将是答案.所以这是优化的代码:

print 2**4 * 3**2 * 5 * 7 * 11 * 13 * 17 * 19
Run Code Online (Sandbox Code Playgroud)