【发布时间】:2017-05-29 00:34:44
【问题描述】:
这是一个 Project Euler 挑战,我试图找到能被 1 到 20 的所有数字整除的最小正数?
我想出的逻辑似乎运行得很慢。它已经运行了最后 4 分钟,但仍然没有找到号码。我试图弄清楚a)这个逻辑正确吗? b) 为什么这需要这么长时间? c) 有人可以给我一个关于更有效的替代逻辑的提示吗?
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
smallest_num = 2520
while smallest_num >= 2520:
divisor = 2
while smallest_num % divisor == 0 and divisor < 21:
print("Smalles num = {} and Divisor = {}").format(smallest_num, divisor)
divisor += 1
smallest_num += 1
print("Smallest number is: {}").format(smallest_num)
这仍在处理中,到目前为止我的终端看起来像这样
【问题讨论】:
-
这段代码将永远运行。
-
您可以优化它,使其不会检查 1 到 20 之间的每个数字。例如,通过检查 20,您也检查了 1、2、4、5 和 10。跨度>
-
while smallest_num >= 2520:没有理由停下来,所以不,你的逻辑不正确。此外,您获得 2520 的原因是您可以首先在较小的问题上测试您的逻辑。尝试编写一个不包含 2520 的程序,但在考虑 1 到 10 的数字时会产生 2520 作为输出。 -
对于编程循环,通常最好手动写出前几次迭代中变量会发生什么。这通常可以诊断出循环是否会停止或实现其目标的问题
-
您正在寻找最小公倍数,而这种蛮力方法是最糟糕的方法。你想做的是素数分解。 en.wikipedia.org/wiki/Least_common_multiple 或者使用欧几里得算法,找到GCD并做一些除法。
标签: python