[Solved]: A puzzle related to nested loops

Problem Detail: For a given input $N$, how many times does the enclosed statement executes?

for $i$ in $1ldots N$ loop
$quad$for $j$ in $1ldots i$ loop
$quad$$quad$for $k$ in $ildots j$ loop
$quad$$quad$$quad$$sum = sum + i$ ;
$quad$$quad$end loop;
$quad$end loop;
end loop;

Can anyone figure out an easy way or a formula to do this in general. Please explain.

Asked By : Vishnu Vivek

Answered By : Bartosz Przybylski

You need to solve simple formula $sum_{i=1}^Nsum_{j=1}^isum_{k=i}^j1$ this will give you overall result of $frac{1}{6}N(N+1)(N+2)$ Math is easy to do here but I used Wolfram Alpha
Best Answer from StackOverflow

Question Source : http://cs.stackexchange.com/questions/7008

Leave a Reply