【发布时间】:2015-01-23 03:22:18
【问题描述】:
我目前正在尝试解决问题“可以被 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 之间的所有数字的可分性吗?如果一个数可以被 2 和 3 整除,那么它还能被 1 到 20 之间的哪些数整除?
-
这不是功课,我只是在我的学术之外自学python。好点,谢谢!
-
您可能有兴趣在谷歌上搜索“最小公倍数”。
-
您的算法有误。有关 C 中的解决方案,请参阅 stackoverflow.com/questions/8416395/…。