gpt4 book ai didi

ruby - Ruby 计算速度慢?欧拉计划 #5

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:16 25 4
gpt4 key购买 nike

这个问题引用了Project Euler Problem 5 ,所以谨防剧透!问题 5:

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?

我用 Ruby 编写了以下代码作为问题 5 的解决方案。

num = 2520
until (1..20).all?{|x| num % x == 0}
num += 1
end
puts "#{num}"

但是,每当我运行脚本时,它就会挂起。请注意,我在基本案例 2520 上针对 1 到 10 的范围测试了相同的方法,并且效果很好。

为什么它适用于更简单的情况而不适用于更高级的情况?我能做些什么来修复我所拥有的?

最佳答案

它很慢,因为答案超过 2 亿,而您要以 1 为步长计算到它。这需要一段时间。您需要更好的算法。

关于ruby - Ruby 计算速度慢?欧拉计划 #5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16805544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com