1

I am having trouble calculating the time complexity for these for loops:

for(int i=0; i<len; i++){
    countOne++;
    for(int j=i/2; j<len; j++){
        countTwo++;
        for(int k=i/2; k<len; k++){
            countThree++;
        }
    }
}

I don't understand how to calculate the time complexity for the 2 inner-most loops.

4
  • 3
    What, precisely, do you mean by "calculate the running time"? Commented Oct 13, 2013 at 5:27
  • 1
    I think you want to calculate complexity Big O ? right ? Commented Oct 13, 2013 at 5:29
  • yes, Big O running time. I would like to know the running time of each line, specifically the 2 inner loops. For example, I believe the first for loop runs n+1 times. Commented Oct 13, 2013 at 5:41
  • @AdrienneKeck I think the term you are looking for is time complexity, not running time (which is most commonly referred to as run time). It's impossible to calculate the run time of your code since this depends on an infinitely large number of additional factors. Commented Oct 13, 2013 at 6:22

2 Answers 2

3

This sounds like a Big Oh question. But you should specify that in the future.

  • countOne is incremented len times.
  • For every i, countTwo is incremented len-i/2 times. i goes from 0 to len-1, so countTwo is incremented between len/2 and len (or O(len)) times per i, or O(len2) in total.
  • similar story for countThree, it's incremented O(len3) times.

Therefore the entire algorithm is O(len3).

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

Comments

0

You proceed methodically with Sigma notation:

enter image description here

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.