我正在學習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