# Given the volume of a stack of cubes, find the number of cubes

I was trying to solve a code challenge but could not wrap my head around the math.

Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of $$n^3$$, the cube above will have volume of $$(n-1)^3$$ and so on until the top which will have a volume of $$1^3$$.

You are given the total volume $$m$$ of the building. Being given $$m$$ can you find the number $$n$$ of cubes you will have to build?

So the equation for the volume of a stack is $$n^3 + (n-1)^3 + ... + 1^3 = m$$.

How do I find the value of $$n$$?

As explained and proven here, the sum of the first $n$ cubes is $1^3+2^3+\dots n^3=\left( n(n+1)/2 \right)^2$.

Now given:$$m=\left( n(n+1)/2 \right)^2$$ you need to find $n$. So first take the square root to get: $$2m^{1/2}=n^2+n$$ rearrange to $$n^2+n-2m^{1/2}=0$$ Now solve this quadratic and you want the positive root

• Unfortunately, this approach is going to result in several rounding errors/floating-point imprecision. – AleksandrH Dec 4 '18 at 2:43

if it is a programming problem, then what is asked is

function find_n_from(m) {
var n = 0;
var volume = 0;
while(volume < m) {
n++;
volume += n*n*n;
}
if (volume != m) "problem..";
return n;
}

• Of course if it is a programming problem it is off topic (and trivial, as you demonstrate, and it is pretty elementary even as a maths problem). – Conrad Turner May 21 '16 at 8:23
• @ConradTurner : what is not off topic is telling to the mathematicians that there are not "only the maths" :) – reuns May 21 '16 at 8:24
• Would you like to try that last comment again in English? – Conrad Turner May 21 '16 at 8:26
• @ConradTurner : I can't do much better sry – reuns May 21 '16 at 8:27
• Thanks, that makes it clear, but does that not support the suggestion that it is off topic? It is not as though maths:SE is the only forum here, or that many of the posters here do not hang out at some of those. Also, completely separate from the rest of this comment: It might be obvious to us what programming language or languages you code is in but should you not say what it is? – Conrad Turner May 21 '16 at 8:44