Calculating the amount of cubes needed to form a sum
When there's math to be done, always check if some formula exists

$$1^3+2^3 + \dots+n^3 = m = (1+2 + \dots+n)^2$$

in conjunction with some other formula (interesting wikipedia article title)

$$\sum^n_{k=1}k = \frac{n(n+1)}{2}$$

you get some equation for the result

$$\sqrt{m} = 1+2 + \dots+n = \sum^n_{k=1}k = \frac{n(n+1)}{2}$$
and maybe some closed formula

$$
\begin{align}
\sqrt{m} &amp;= \frac{n(n+1)}{2}\\
2\sqrt{m} &amp;= n(n+1)\\
2\sqrt{m} &amp;= n^2+n\\
0&amp;= n^2+n - 2\sqrt{m}
\end{align}
$$

Which has the 2 solutions

$$n_{1,2} = -\frac12 \pm\sqrt{\frac14+2\sqrt{m}}$$

As \$n\$ should be a positive number, only the first solution makes sense.

Return \$ -\frac12 +\sqrt{\frac14+2\sqrt{m}}\$ if it is an integer or \$-1\$ otherwise.

The results are:

$$
\begin{array}{r|r}
m &amp; n\\
\hline
4183059834009 &amp; 2022\\
24723578342962 &amp; -1\\
135440716410000 &amp; 4824\\
40539911473216 &amp; 3568\\
\end{array}
$$

24723578342962 is a very close call, because

$$\sum^{3153}_{k=1}k^3=24723578342961$$

is only 1 off. The floating point result is \$n=3153.00000000003\$. If you don't want to get false positives due to floating point precision (lack thereof), you can do the check by converting the result to some integer type and see if you get the exact number by doing the calculations with that.