加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

慢Ruby计算?项目欧拉#5

发布时间:2020-12-17 01:29:44 所属栏目:百科 来源:网络整理
导读:这个问题引用了 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
这个问题引用了 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读