Better way to write this in Ruby?
I'm new to Ruby. After a ton of refactoring I came down to this. Is there a better way to wr开发者_如何学Pythonite this?
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
What about solving it directly?
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
Though I don't know if tri_num?
is a good name. Usually a function ending with a ? should return true
or false
.
Yes.
def tri_num?(n)
1.upto(n-1) do |i|
return i if i * (i + 1) / 2 == n
end
raise InvalidTree
end
I thought the same as dantswain, basically invert the equation:
=> i * (i + 1) / 2 = n
=> i * (i + 1) = 2*n
=> i^2 + i = 2*n
=> i^2 + i -2*n = 0
And the solutions for the above are:
i = (-1 +- sqrt(1+8n))/2
Here I don't consider the -
solution as it will give negative for any value of n bigger than 0, in the end the code is:
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
精彩评论