Calculating the product of 3 numbers in an iterative way Let $x,y,z \in \mathbf{N}$ and imagine the following procedure :


*

*Initialize $sum = 0$

*Choose randomly a number out $x,y,z$ and add to $sum$ the product of the two others, e.g. if $x$ had chosen we update $sum = sum + y \cdot z $ and subtract $1$ from $x$, consequently the new triplet becomes $(x-1), y, z$

*Iterate 1. and 2. till one of the triplet element is zero.
The question is, what is the value of $sum$ at the end of the procedure. The answer is $sum = x \cdot y \cdot z$. How do I prove it? Is it true for any $n>3$ integers ?
 A: Imagine you have $x\cdot y \cdot z$ unit cubes, and you use them to build an $x\times y \times z$ block, and you have an empty bag next to it. Now, take all the cubes that make up a random face (that is, one layer), and put them in the bag.
If you happen to choose a $y\times z$-face, then you are putting $y\cdot z$ cubes in the bag, and the resulting block is now $(x-1)\times y \times z$ large.
Repeat this until there are no cubes left in the block. The number of cubes in the bag is your sum variable.
A: If you label the variables with an index, namely $x_0, y_0, z_0$ and $x_k, y_k, z_k$ after the $k$th iteration, you have the loop invariant
$$\mathrm{sum}_k  + x_k y_k z_k = x_0 y_0 z_0.$$
This follows from $\mathrm{sum}_0=0\;$ and
$$ x_k y_k z_k = (x_k-1) y_k z_k + y_k z_k 
= x_k (y_k-1) z_k + x_k z_k
= x_k y_k (z_k-1) + x_k y_k.$$
If the iteration stops because one of $x_n, y_n, z_n$ is zero, the result is
$$\mathrm{sum} = \mathrm{sum}_n  + 0 = x_0 y_0 z_0.$$
And obviously this argument can be generalized to any $n > 3$ starting values $x_1,\dots\ x_n \in \mathbb{N}$.
