# Understanding the mathematical intuition/logic behind the “easy” solution to this loop algorithm problem.

I realize this may seem a bit off-topic because it deals with a computer algorithm and nested loops, but it's from my discrete mathematics course, and the quick solution presented in the book seems to suggest there's some mathematical intuition involved in arriving at the answer:

Basically, you declare a variable named $count$ and initialize it with the value of $0$. The outer loop runs $3$ times, while the nested inner loop runs $4$ times. That is, the entire algorithm runs $12$ times. During each run, the variable $count$ is assigned the sum of its former value and the product of the current run's $i$ and $j$ values.

I worked this out on paper in a rather brute force approach and got an answer of $60$ for the final value of $count$ after the loops terminate, which is correct.

The book presents the following concise solution:

$1(1 + 2 + 3 + 4) + 2(1 + 2 + 3 + 4) + 3(1 + 2 + 3 + 4) = 60$

You have a formula for algorithm $\sum \limits_{i = 1}^3 \sum \limits_{j = 1}^4 i j = \sum \limits_{i = 1}^3(i \cdot \sum \limits_{j = 1}^4 j)$, so you have your formula $$1(1+2+3+4)+2(1+2+3+4)+3(1+2+3+4)=60$$

• Interesting, thank you! That makes perfect sense. – AleksandrH Jun 5 '17 at 22:06