To clarify before I begin, this is NOT homework but rather I am studying for my exam. I have given solutions for the questions below. I would like some constructive feedback.
Thanks for the feedback for whoever left it in my last question. Below I have given in detail solutions to why i think the answer is so.
Find running time in terms of O(n) notation.
int y=0;
for(int j=1; j*j<=n; j++)// runs from 1->j=sqrt(n) times
y++; //constant - c
Therefore, run time is c x n^1/2 = O(n^1/2)
Q2.
int b=0;
for(int i=n; i>0; i--) //runs from n->1
for(int j=0; j<i; j++) // runs from 0 to i
b=b+5; //constant
for each value of j (1,2...,n) inner loop runs i times constant = ci.
– nc+(n-1)+...+2c+1c = c(n+..+2+1) = cn(n+1)/2 = O(n^2) run time.
Q3.
int y=1;
int j=0;
for(j=1; j<=2n; j=j+2) //runs 2n times, increments by 2
y=y+i; //constant c
int s=0;
for(i=1; i<=j; i++) // not a nested for loop, therefore runs n times
s++;
running time: O(n)
Q4.
int x=0; //constant
for(int i=1; i<=n; i=i*3) //runs log_3 (n) times
{
if(i%2 != 0) // for values above will always be 1
for(int j=0; j<i; j++) // runs from 0 to log_3(n)
x++;
}
so we have clog_3(n)xclog_3(n) = O(log_3(n))^2
Ok, first three are out of doubt (I believe, all are correct).
But with Q4 there is a problem.
Your answer is a little bit incorrect. Definitely, the result is not
O(log_3(n))^2. The case is in the inner loop, which goes exactly onlyO(log_3(n))times. And, not from0-log_3(n)but from0-m(wheremis obviously correlated toi).Assuming all above, I think the right answer is
O(mlog3(n)). But if someone think that i was wrong, please correct me.