3
void f(int n)
{
  for(int i =1; i<=n; i++){
    if(i % (int)sqrt(n)==0){
      for(int k=0; k< pow(i,3); k++){
        //do something
      }
    }
  }
}

My thinking process: number of times execute if statement: sum i=1 to n (theta(1)).

number of times execute things inside if: sum i=1 to sqrt(n) (for loop)

number of times execute for loops: sum k=0 to i^3 (theta(1)) = i^3

This will give me: theta(n) + sum i=0 to sqrt(n) (theta(i^3)) = theta(n) + theta(n^2)

which gives me theta(n^2)

The answer key he gave is theta(n^3.5)

I am just wondering if i made any mistake on my thinking process. I have asked my professor twice about this question. Just want to see if there is anything I didn't see before I bother him again.. Thanks!

2 Answers 2

1

Using Sigma notation, I came up with the exact closed-form.

Besides, the formula below assumes the process, which doesn't verify the condition that executes the innermost loop, is negligible.

enter image description here

It's up to you to determine tight order of growth bounds, because of flooring function and square root etc.

Further details here: https://math.stackexchange.com/questions/1840414/summation-with-floor-and-square-root-functions-tight-bounds

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

Comments

0
void f(int n) {   
  for(int i =1; i<=n; i++){     //---   n times
    if(i % (int)sqrt(n)==0){    // ---  2 times (constant)
      for(int k=0; k< pow(i,3); k++){  // sqrt(n)^3 and n^3 times
        //do something
      }
    }   
  } 
}

Taking the highest order term it should be Theta(n^3)

Assuming do something is constant

c = do somrthing + plus running cost of single iteration of inner loop

a = runnning cost of running single iteration of outer most loop

b = running cost of if block Thinking more about it cn^3/2 + cn^3 + a*n + b*2)

Taking the highest order term Theta(n^3) or since c is same coefficient for both the n^3 and n^3/2 we can reduce it

= cn^3 + cn^3/2

= cn^3(n^1/2+1)

~ cn^3 * n^1/2

= cn^3.5

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.