construct a triangle given n items

194 Views Asked by At

If $n$ number of inputs are given, then how can I find the number of levels triangle will have.

e.g. If $10$ elements are given, there will be $4$ level triangle. If $21$ elements are given, there will be $6$ level triangle etc.

triangles of dots

1

There are 1 best solutions below

1
On BEST ANSWER

In general these numbers are called triangular numbers (which I presume you already know because of the image), and in general the number of dots in the $m$-level triangle is $$\binom{m+1}{2}=\frac{m(m+1)}{2}$$

Hence given $n$ dots you just want to solve the following equation for $m$:

$$\frac{m(m+1)}{2}=n$$

Rearranging, we get $$m^2+m-2n=0$$ and solving this quadratic we get $$m=\frac{-1\pm\sqrt{1+8n}}{2}$$

Notice that there is an extraneous solution, but it is easy to identify since for $n\ge0$ exactly one of the solutions is positive. Hence the number you want is

$$m=\frac{-1+\sqrt{1+8n}}{2}$$

Note that this may not always be an integer since we can't always generate a perfect triangle with $n$ dots, but we still have a useful result even when $m$ is not an integer: The biggest triangle we can make with the $n$ dots is a $\lfloor m\rfloor$level triangle.