Consider a for (i=1; i <= n; i++)
loop for (i=1; i <= n; i++)
. It is trivial to see that it loops n times. We can do it like:
* * * * *
Now that you have two nested loops, your inner loop will loop n (n + 1) / 2 times. Notice how this forms a triangle, and in fact, numbers of this shape are known as triangular numbers .
* * * * * * * * * * * * * * *
So, if we extend this to another dimension, it forms a tetrahedron. Since I cannot do 3D here, imagine that each of these layers is stacked on top of each other.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
They are called tetrahedral numbers , which are generated by this formula:
n(n+1)(n+2)
You should be able to confirm that this is indeed the case with a small test program.
If we notice that 6 = 3 !, itβs not so difficult to see how this template generalizes to higher sizes :
n(n+1)(n+2)...(n+r-1)
Here r is the number of nested loops.
source share