1

How do I find the O - notation complexity for the following?

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

I read the guide on Big - O and other posts on Big -O complexity, but I'm still lost.

  • FWIW, start by looking up for an explicit formula for the number of iterations of the above loop. Google is your friend. – Doc Brown Nov 22 '16 at 7:28
1

I just learned Big O notation this semester, but from my understanding O notation looks at the complexity of an algorithm. In this case the loop runs 2n times so you'll be doing sum++ 2n times so it would be O(2n).

Big O notation looks at the worst case scenario with very large inputs so you can drop the constant 2, since at very very large n's or inputs the 2 doesn't have a really large affect on the complexity so Big O would be O(n).

You could probably look up examples of O(n), O(logn), O(2^n), O(n^2) so you can see what algorithms with these complexities look like.

  • 1
    No matter how large n is, multiplying it by two will always have a large effect. There is a different reason for dropping the constant coefficient. If we didn't, we would have to count the individual operations: in each iteration you increment i, increment sum, calculate n*2 and perform a comparison - 4 operations, so it's O(8n). But does each of these operation has the same cost? And maybe the machine is slow so each operation costs twice as much? To avoid dwelling in these specifics, it was decided that we should ignore the constant coefficient. – Idan Arye Nov 22 '16 at 2:11
  • 1
    @Idan Arye just to confirm, O(2N) reduces to O(N), correct? – morbidCode Nov 22 '16 at 3:44
  • @morbidCode correct – Idan Arye Nov 22 '16 at 9:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.