Domanda

I wonder how many times the 2 piece of code will be executed. Both of them are n times or one of them is n+1 ?

int sum=0;
for (int i = 1; i <= n; i++) 
sum = sum + i; 

AND

int sum=0;
for (int i = 1; i <= n; ++i) 
sum = sum + i; 

Is there anyone to help me ?

EDIT Sınce I got so many , bad comment. I decided to give my real intent to ask this.

int sum = 0;
for (int i = 1; i <= n; ++i)
sum = sum + f1(i, n);}

int f1(int x, int n) { 
int sum = 0; 
for (int i = 1; i <= n; i++) 
sum = sum + i; 
return (x + sum); } 

The exact complexity of this code snippet is O(n*(n+1)) and I want to learn why there is(n+1) instead of o(n*n)

È stato utile?

Soluzione

It doesn't matter which one you use, the program output will be identical; i++ and ++i are not the termination conditions in the for loop but are statements evaluated at the end of each iteration.

Note however that ++i will never be slower than i++; as conceptually an object copy has to be taken for the latter. A good compiler will optimise out the copy though.

And a point of style: please indent the line sum = sum + i;; it's hard to read otherwise.

Altri suggerimenti

I think the code complexity of the code is O(n^2). It doesn't matter about looping for n+1 in complexity. O(n+1) = O(n-1) = O(n) so all are same and the complexity can be said to be n^2.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top