7

I'm trying to figure out the time complexity of this pseudocode given algorithm:

sum = 0;
for (i = 1; i <= n; i++)
    for (j = 1; j <= n / 6; j++)
        sum = sum + 1;

I know that the first line runs

n times

But I'm not sure about the second line.

7
  • 1
    time complexity = sum ? :) (n*n/6) Commented Jan 15, 2016 at 1:10
  • 2
    Wouldn't that just be O(n^2)? Seems to simple. Commented Jan 15, 2016 at 1:11
  • It doesn't always have to be hard :) Commented Jan 15, 2016 at 1:12
  • Okay, if I understand this correctly, if the second loop were to be j=1 to n/i, would the resulting complexity be (n*n/i) which is again O(n^2)? Commented Jan 15, 2016 at 1:14
  • Yes @Aede, did you check the answers, they explain it. :) Commented Jan 15, 2016 at 1:17

3 Answers 3

4

Using Sigma notation, we can find the asymptotic bounds of your algorithm as follows:

enter image description here

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

Comments

3

Here you have a simple double loop:

for i=1;i<=n;i++
   for j=1; j<=n/6; j++

so if you count how many times the body of the loop will be executed (i.e. how many times this line of code sum = sum + 1; will be executed), you will see it's:

n*n/6 = n²/6

which in terms of big-O notation is:

O(n²)

because we do not really care for the constant term, because as n grows, the constant term makes no (big) difference if it's there or not!


When and only when you fully realize what I am saying, you can go deeper with this nice question: Big O, how do you calculate/approximate it?


However, please notice that such questions are more appropriate for the Theoretical Computer Science, rather than SO.

Comments

1

You make n*n/6 operations, thus, the time complexity is O(n^2/6) = O(n^2).

1 Comment

More precisely, n * (n / 6) operations: the complexity is the same, but the result differs.

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.