Reverse of sum of (1,2,...,n)

127 Views Asked by At

I'm developing a game. To reach level 6, a player needs 1+2+3+4+5+6=21 points. Points need to reach level X = X.(X+1)/2

On the database, I store the points, not the level. I need to get a reverse function, on wich I give the total points a player have and the function returns on wich level that player is.

2

There are 2 best solutions below

1
On BEST ANSWER

This is just a quadratic to solve $\dfrac{X(X+1)}{2}=p\iff X^2+X-2p=0$

Application of the formula gives $\ X=\frac 12(\sqrt{8p+1}-1)$

It gives you a decimal level, so you are probably more interested in calculating floor(X) to get an integer level.

1
On

Multiply the number by $2$, take the square root, and round down.