4 ms·
Worked out the math to get rid of the loop. def efficient(x) num = (Math.sqrt(2 * x + 0.25) - 0.5).floor num2 = (num**2 + num)/2 [x-num2, num]
by xenophanes 16y ago
Worked out the math to get rid of the loop.
def efficient(x)
num = (Math.sqrt(2 * x + 0.25) - 0.5).floor
num2 = (num**2 + num)/2
[x-num2, num]
end
Edit: Or:
def efficient2(x)
num = (Math.sqrt(2 * x + 0.25) - 0.5)
num2 = ((num - num.floor) * num).round
[num2, num.floor]
end