2
$\begingroup$

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:

enter image description here

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$

Could someone please help me understand why this is a correct breakdown of the algorithm's logic?

$\endgroup$
2
$\begingroup$

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$$

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.