Show the step to find the total operations of the algorithm
Bellow is some Java code for the question:
int total1 = 0;
开发者_开发百科int total2 = 0;
for (int x = 0; x <= n; x++)
total1 = total1 + x;
for (int y = 1; y < n; y++)
total2 += total1 * y;
Based on the question above, I do an answer likes bellow. Please help me check my answer right or wrong. Thanks for your helping.
Operation Number of operations
-------------------------------------
Assignment n² + 1
Addition n²
Multiplication n²
Total Operation 3n² + 1
Let's start with this: Why do you think there are n^2 + 1 times assignments?
No, it's not correct.
The second loop goes from 1 to n-1, so that is n-1 iterations.
What do you mean by "n²" operations? Is that n squared?
int total1 = 0;
1 assignment
int total2 = 0;
1 assignment
for (int x = 0; x <= n; x++)
n+2 comparisons
n+1 additions
n+2 assignments
total1 = total1 + x;
n+1 additions
n+1 assignments
for (int y = 1; y < n; y++)
n comparisons
n-1 additions
n assignments
total2 += total1 * y;
n-1 multiplications
n-1 assignments
Summed up:
assignments: 1+1+n+2+n+1+n+n-1 = 4n + 4
additions: n+1+n+1+n-1 = 3n+2
multiplications: n-1
comparisons: n+2 + n = 2n+2
Total: 10n + 7 operations
With n > 1, as for n = 0 some terms get wrong. Quadratic terms in general only appear with nested loops. Don't forget the for(...) parts. An increment is an add + assignment - although some architectures might do it in one step. No jumping operations counted here.
精彩评论