0

here is the question:

for(i=1;i<=n,i++){

      for(j=2*i;j<=n,j++){

        puts("hello"):
       }
}

Here is my solution: the outer loop has 1+n+1+n running time and the second for loops has n*(1+n/2+1+n/2)run times, and the third statement has n*n/2 run times. the second and third statetment very confused me, i don't know whether my calculation is correct or not, any clarification would be appreciated, thanks in advnace.

1 Answer 1

1

Since you are allowed to use Big-O notation, you do not have to write down all the details.

Let T(n) be the running time of your algorithm when the input size is n.

First of all, puts("hello") is O(1). As you can clearly see from the code, puts("hello") has been executed less than n^2 times. Also note that if the outer loop was changed (reduced) to

for (i = 0; i < n / 4; ++i)

the inner loop will be executed for at least n/2 times for every i, that means the statement puts("hello") will be executed for at least n/4 * n/2 = n^2/8.

Now as discussed above, we have n^2/8 <= T(n) <= n^2. Therefore we have T(n) = O(n^2) (the analysis is tight, that means we have T(n) = \Theta(n^2)).

If you have problem understanding the concepts of Big-O and Theta, you may refer to this video: https://youtu.be/6Ol2JbwoJp0

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

5 Comments

how come the outer loop is reduced to n/4 times? i don't quite get it, could you please explained it more clearly. Thanks bro
yes i just very confused with the big o notation, so i have to do it the hard way. And i want to know whether my algorithm is correct or not?
also the "puts("hello") has been executed less than n^2 times", n^2 should be n/2 right?
Let T(n) be the running time when the input size is n, an algorithm is said to run in O(n^2) , if there is a positive number C and a threshold n_0, such that whenever n is larger than n_0, we have T(n) <= C * n^2. Informally speaking, an algorithm runs in O(n^2) means its running time is bounded by C* n^2 for large input size.
"n^2 should be n/2 right?" well for each fixed i, "puts("hello") has been executed for less than n times", as we have n different i, overall puts("hello") was executed for less than n^2. To get the running time in Big-O notation, you need to figure out the "upper bound" of the running time. In our case the upper bound is n^2.

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.