Just a confusion.... A portion of a C++ sample code is as follows
I just re-edit the whole post. Sorry for any confusion
int i, j;
i = 0; // c1
j = 0; // c2
while (i < n) // (n+1)c3
{
i++; // n c4
while ( j < i) // (2+3+....+n+(n+1)c5
{
j++; // (1+2+...+n)c6
}
j = 0; // c7
}
Clearly, c1, c2, and c7 are constant. We are not interested in those, and they don't really matter in determing the running time.
What I don't understand is c5 and c6.
Why is it 2+3+4...+n+(n+1) for c5? Why does it start with 2, instead of 1+2+3...+(n+1)??? Note that we can rewrite C5 -> (n*(n-1)/2) + n
For c6, this cominbation can be rewritten as n*(n-1)/2
Initially I thought C6 is n, because C6 depends on two conditions, the first while and second while loop. But since j will always go back to 0, so we are really depending on the first while loop. Because n < n is false, then the j++ wil run maxiumly n-th time.
n = 3
0 < 3, 1, 0 < 1, 1, 0
1 < 3, 2, 0 < 1, 1, 0
2 < 3, 3, 0 < 1, 1, 0
3 < 3 fail.
Can someone please explicitly explain how C5 and C6 are deteremined? I am sorry if this problem sound dumb to the experts Thank you!