为什么我的代码不会停止运行?
我正在尝试解决欧拉项目中的问题#5。该代码适用于示例,当我检查从 1 到 10 的数字时,我得到的结果是 2520,这是正确的。但是当我检查 1 到 20 之间的数字时,代码并没有停止运行。
这里是:
num = 0
while true
num += 1
check = true
for i in 1..20
break unless check
check = num%i==0
end
break if check
end
File.open("__RESULT__.txt", "w+").write num
I'm trying to solve Problem #5 in Project Euler. The code works for the example, when I check the numbers from 1 to 10 I get 2520 as a result, which is right. But when I check for the numbers from 1 to 20, the code doesn't stop running.
Here it is:
num = 0
while true
num += 1
check = true
for i in 1..20
break unless check
check = num%i==0
end
break if check
end
File.open("__RESULT__.txt", "w+").write num
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅通过计算每个可能的解决方案无法找到该问题的解决方案。解是如此之大,需要几天(也许几年)才能计算出来。
有一个更聪明的解决方案,使用质数来写下数字。
给出的示例(2520 是可被数字 1 到 10 整除的最小数字)可以这样写:
现在可以使用所用的最大幂来计算可被这些数字整除的最小数字对每个素数:
可以对数字 1 到 20 执行相同的操作(甚至可以手动执行)
最后提示:答案大于 100.000.000 但小于 10 亿,因此可以 如果高效完成,只需几分钟即可计算出
The solution for that problem can not be found by just calculating every possible solution. The solution is so big, that it will take days (maybe years) to calculate.
There is a smarter solution using prime numbers to write down the numbers.
The example that is given (2520 is the smallest number that is divisable by the numbers 1 through 10) can be written down like this:
Now the smallest number that can be divided by these, can be calculated by using the maximum power that is used on each prime:
The same can be performed (even by hand) on the numbers 1 through 20
Last hint: the answer is larger than 100.000.000 but less that a billion, so it can be calculated in minutes if done efficiently
这个问题本质上是要求你找到前 20 个数字的最小公倍数……
The Question essentially asks you to find the LCM of the first 20 numbers...
一个更简单的解决方案是使用您的算法,但增加 2520 而不是 1,这是我的 C++ 解决方案。
正如您在上面看到的,我也从数字 2520 开始,并将 i 设置为等于 11。我们可以进行这些优化,因为我们已经在问题中获得了必要的信息。
A far simpler solution would be to use your algorithm but increment by 2520 rather than 1, here is my C++ solution.
As you can see above, I also start at the number 2520, and set i to equal 11. We can make these optimizations, as we have been given the necessary information in the question.