我目前正在尝试解决问题“可以被 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 问题作为其中的一部分。