【发布时间】:2018-04-17 16:56:56
【问题描述】:
我正在尝试解决项目欧拉问题:
2520 是可以除以每个数字的最小数字 从 1 到 10 没有任何余数。最小的正数是多少 能被 1 到 20 的所有数整除的数?
我想出了下面的python解决方案,但是有什么方法可以循环if中的数字,而不必全部写出来。
def smallest_m():
start=1
while True:
if start%2==0 and start%3==0 and start%4==0 and start%5==0 and start%5==0 and start%6==0 and start%7==0 and start%8==0 and start%9==0 and start%10==0 and start%11==0 and start%12==0 and start%13==0 and start%14==0 and start%15==0 and start%16==0 and start%17==0 and start%18==0 and start%19==0 and start%20==0:
print(start)
break
else:
start+=1
smallest_m()
【问题讨论】:
-
您可以使用范围来枚举 2 到 20 之间的所有值:
for divisor in range(2,20+1): -
要被 10 整除的数字需要以零结尾。因此,您可以从 10 点开始并在 10 秒内向上移动。这将使您的代码速度提高 10 倍!
-
for in range()似乎没有给出正确答案。 -
@CodeCupboard 你没看懂这个问题。这个数字应该能被从一到二十的所有数字整除
-
我明白这一点,但是检查一个不以零结尾的数字是没有意义的,因为它总是失败。代码在每个循环中都有增量开始。