How many times has the $S$ value changed during the program? If $n = 20$. Get the general formula $f(n)$ for calculating the number of operations

26 Views Asked by At

How many times has the $S$ value changed during the program? If $n = 20$. Get the general formula $f(n)$ for calculating the number of operations

 #include <iostream>
 using namespace std;
 int main() {
 int i, j, k, m, n=20, s = 0;
 for (i = 1; i <= n; i++)
 {
    s = s + C[i][1][2][3];
    for (j = 1; j <= n; j++)
    {
        s = s + C[i][j][4][3];
        for (k = 1; k <= i + j; k++)
        {
            s = s + C[i][j][k][10];
        }
    }
}
for (m = 1; m <= i + j; m++) { s = s + C[i][j][k][m]; }

cout << s << "\n";
return 0;

}

In the attached photo, I wrote my formula, which I got.

In the attached photo, I wrote my formula, which I got. But I'm not sure I did it right. If I count just in the program, then I get a different value. Where am I going wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

The correct formula is:

$$\sum_{i=1}^n \left(1+\sum_{j=1}^n\left(1+\sum_{k=1}^{i+j}1\right)\right)+\sum_{m=1}^{2n+2} 1$$ Or:

$$\sum_{i=1}^n \left(1+\sum_{j=1}^n\left(1+i +j\right)\right)+2n+2$$ or: $$\sum_{i=1}^n\left(1+n+ni+\frac{n(n+1)}2\right)+(2n+2)$$

Finally:

$$n+n^2+\frac{n^2(n+1)}{2}+\frac{n^2(n+1)}2+(2n+2)\\=n^3+2n^2+3n+2=8862$$


A slightly quicker calculation is that the average length of the $\sum_k 1$ term is $n+1,$ and there are $n^2$ such sums, so the value can be written as:

$$n^2(n+1)+\sum_i\left(1+\sum_j 1\right) +2(n+2)$$