Ruby 写了一段 Ruby 代码,但是运行卡住,循环问题

yz00 · 2015年06月09日 · 最后由 yz00 回复于 2015年06月09日 · 1750 次阅读

2520 is the smallest nuber that can be diveded by each of the number 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? 朋友发来一道题来做,我一看原来是求 1 到 20 的最小公倍数,然后就写了下面的代码,运行之后输入 20 就卡住了,出不来结果,但是输得数字小点就可以算出来,是不是我的循环写的有问题,想请大家帮忙看下怎么优化一下,有资料最好(本人用的 rubyV2.1.5)

b=Array.new
c= gets.chomp
a=1..c.to_i
jc=1
a.each do |elem|  
    b<<elem.to_i
end
b.each do |e|         #阶乘
    jc *= e 
end
x=b.max 
co = 1*x
x.upto(jc) do |i|         
        sum=0
        b.each do |f|
            sum = (i%f) +sum
        end
        if sum == 0
            co = i
            break
    end
end
puts "The common multiple is #{co}" 

@luikore 谢谢,让我知道了更简便的方法。

1.upto(20).reduce(:lcm)

也可以这样……

@msg7086 谢谢。初学,刚去看了 reduce 是怎么回事。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号