var r = 0;
for(var i=1; i<=2*n; i++) {
for(var j=1; j<=n; j++) {
for(var k=j; k<=n; k++) {
r = r + (i - j);
}
}
}
I'm trying to use summation to solve for it, but I'm having a bit of trouble.
I got this summation:
$$ \sum_{i=1}^{2n} \sum_{j=1}^{n} \sum_{k=j}^{n} i-j $$
But after trying to get a closed form for this, I got $-n^4 + n^2$, which is surely not the answer.
Could you guys help me?
$$\sum_{i=1}^{2n} \sum_{j=1}^{n} \sum_{k=j}^{n} i-j$$ $$\sum_{i=1}^{2n} \sum_{j=1}^{n} (i-j)\cdot(n-j+1)$$ $$\sum_{i=1}^{2n} \sum_{j=1}^{n} (ni-ij+i-nj+j^2-j)$$ $$\sum_{i=1}^{2n} (ni\cdot n-i\frac{n(n+1)}{2}+in-n\frac{n(n+1)}{2}+\frac{n(n+1)(2n+1)}{6}-\frac{n(n+1)}{2})$$ $$\sum_{i=1}^{2n} \left(i( n^2-\frac{n(n+1)}{2}+n)-\frac{n(n^2+3n+2)}{6}\right)$$
$$\sum_{i=1}^{2n} \left(i\frac{n(n+1)}{2}-\frac{n(n^2+3n+2)}{6}\right)$$ $$ \frac{2n(2n+1)}{2}\frac{n(n+1)}{2}-2n\frac{n(n^2+3n+2)}{6}=\frac23 n^4 + \frac12 n^3 - \frac16 n^2.$$
But this isn't the time complexity of the loop. It is the value of the triple summation in closed form.