我正在学习Ruby并通过解决Project Euler中的问题来练习它。更多类似ruby的解决方案来解决这个问题?
这是我对问题12的解决方案。
# Project Euler problem: 12
# What is the value of the first triangle number to have over five hundred divisors?
require 'prime'
triangle_number = ->(num){ (num *(num + 1))/2 }
factor_count = ->(num) do
prime_fac = Prime.prime_division(num)
exponents = prime_fac.collect { |item| item.last + 1 }
fac_count = exponents.inject(:*)
end
n = 2
loop do
tn = triangle_number.(n)
if factor_count.(tn) >= 500
puts tn
break
end
n += 1
end
可以对这段代码做任何改进?
是什么' - >'?那是我不知道的1.9个动作吗? – theIV 2010-06-11 16:29:54
其新的lambda语法,而不是d = lambda {| x |如果你只有一个参数,你可以省略括号:' - > num {(num *(num + 1)}在ruby 1.9中你可以写成d = - >(x){x + 1} – RaouL 2010-06-11 16:35:21
1))/ 2}' – 2010-06-11 18:15:17