I just try to solve problem #45 from project-euler using ruby. I know the approach. But I wrote the code, It doesn’t run. I am new to ruby, I don’t know why there has to be so many “end” keyword at the back(Or else the terminal will complain)
Here is the code:
class Test
def initialize()
end
def Triangle(n)
if 1 + 8*n < 0 then
return false
else
i1 = 0.5 * (-1 + Math.sqrt(1 + 8*n))
i2 = 0.5 * (-1 - Math.sqrt(1 + 8*n))
cut_i1 = i1.to_i
cut_i2 = i2.to_i
if (cut_i1 == i1) & (i1 > 0)
return true
else if (cut_i2 == i1) & (i2 > 0)
return true
else
return false
end
end
end
def Pentagonal(n)
delta = 1 + 24*n
if delta < 0 then
return false
else
r1 = (1.0/6) * (1 + Math.sqrt(delta))
r2 = (1.0/6) * (1 - Math.sqrt(delta))
cut_r1 = r1.to_i
cut_r2 = r2.to_i
if (cut_r1 == r1) & (r1 > 0)
return true
else if (cut_r2 == r1) & (r2 > 0)
return true
else
return false
end
end
end
def Hexagonal(n)
delta = 1 + 8*n
if delta < 0 then
return false
else
r1 = 0.25 * (1 + Math.sqrt(delta))
r2 = 0.25 * (1 - Math.sqrt(delta))
cut_r1 = r1.to_i
cut_r2 = r2.to_i
if (cut_r1 == r1) & (r1 > 0)
return true
else if (cut_r2 == r1) & (r2 > 0)
return true
else
return false
end
end
end
end
for i in (1...100)
o = Test.new
print o.Triangle(i)
end
end
end
end
What’s happening. Every time I run the program from the terminal. It shows nothing….
It’s because you are using
else ifinstead ofelsif. Compare:With that in mind, your program does not do what you think it should. Fix the
elsif‘s and see.