[英]Better way to write this in Ruby?
我是Ruby的新手。 經過大量的重構,我得出了這個結論。 有沒有更好的方法來寫這個?
51 def tri_num?(n)
52 i = 1
53 while i < n
54 return i if i * (i + 1) / 2 == n
55 i += 1
56 end
57 raise InvalidTree
58 end
直接解決該怎么辦?
def tri_num? n
i = (0.5*(-1.0 + Math.sqrt(1.0 + 8.0*n))).to_i
if i*(i+1)/2 == n
return i
else
raise InvalidTree
end
end
雖然我不知道tri_num?
是個好名字。 通常一個以?結尾的函數 應該返回true
或false
。
是。
def tri_num?(n)
1.upto(n-1) do |i|
return i if i * (i + 1) / 2 == n
end
raise InvalidTree
end
我以為與Dantswain一樣,基本上將等式反轉:
=> i * (i + 1) / 2 = n
=> i * (i + 1) = 2*n
=> i^2 + i = 2*n
=> i^2 + i -2*n = 0
上面的解決方案是:
i = (-1 +- sqrt(1+8n))/2
這里我不考慮-
解決方案,因為對於任何大於0的n值,它都會給出負數,最后代碼是:
def tri_num?(n)
i = (-1 + Math.sqrt(1 + 8*n))/2.0
return i.to_i if i == i.to_i
raise InvalidTree
end
def tri_num?(n)
(1...n).each do |i|
return i if i * (i + 1) / 2 == n
end
rails InvalidTree # not defined..
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.