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.
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.
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.
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 02:11