当前位置 : 主页 > 编程语言 > ruby >

慢Ruby计算?项目欧拉#5

来源:互联网 收集:自由互联 发布时间:2021-06-23
这个问题引用了 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
这个问题引用了 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,并且它工作得很好.

为什么它适用于更简单的情况,但不适用于更高级的情况?我该怎么做才能解决我的问题?

你将无法像对待别人一样强行解决这个问题.您将需要为它找到更有效的解决方案.

下面的SPOILER

这是一种非常有效的方法(如果这不像Ruby那样道歉):

def find_multiple
  lcm = 1

  (2..20).each do |i|
    lcm *= i / gcd(lcm, i)
  end

  lcm
end

def gcd(a, b)
  while b > 0
    a %= b
    return b if a == 0
    b %= a
  end

  a
end

puts find_multiple

如果您正在寻找更类似Ruby的方法来解决它,您可以使用以下内容(如评论中的steenslag所示):

(1..20).inject(:lcm)
网友评论