0

we're all know that for a code snippet like

for(int i=0;i<n;i++){ //do something}

Has a complexity of O(n) and we can find it:

sum symbol from n=0 to n-1 c1 = c1* ((n-1)*n)/2

What if the code will be :

for(int i=0;i<n;i+=2){ //do something}

I dont only interested in with big o notation but also,exact growth rate function.

Is there anyone to help me ? thanks in advance

4
  • The complexity shall be same as earlier loop. O(n) not O(n^2) Commented Nov 19, 2013 at 9:41
  • As far as I can see, your first statement is O(n), unless something else O(n) happens in the loop... Commented Nov 19, 2013 at 9:42
  • Complexity of both the loops will be same accordint to me and it would be O(n) and not O(n^2) Commented Nov 19, 2013 at 9:43
  • I've corrected it, sorry for mistake Commented Nov 19, 2013 at 9:43

3 Answers 3

3

The //do something shall be executed n/2 times .

Hence complexity = O(n/2) = O(n) (same as the previous loop)

Practically obviously the second loop will take less time as it only executes half the number of statements. However as n grows, the growth in time complexity shall be linear for both the loops.

Sign up to request clarification or add additional context in comments.

Comments

2
for(int i=0;i<n;i++) { /* do something */ }

It has unknown complexity where we don't know about /* do something */. If the loop's body hasn't inner loops based on n. It has complexity O(n).

for(int i=0;i<n;i+=2) { /* do something */ }

As same as above, this has complexity O(n) too. Note that O(n/2) = O(n).

Comments

1

When you take Big O notation , we assume n is a positive set .

N can grow in 2 ways 1-Linearly 2-Exponentially

N grows exponentially if we multiply n by an integer >1. Consider the code snippet

for(i=1;i<n;i=i*2){

}

here n increase by a large value, i.e, 2,4,8,16,32....

N grows linearly if we increment n by an integer>0( The code that you gave grows linearly )

For linear growth, Time complexity is O(n)

For exponential growth, Time complexity is O(logn)

Lets consider another example

for(i=0;i<n*10;i++){//has Complexity O(n)

}

for(i=0;i<n*n;i++){//has Complexity O(n*n) 

}

This is because 10 is a constant and n is not a constant

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.