retagged by
438 views
0 votes
0 votes
What is the time complexity of the following program?

main()
{
 i = n;

while(i>=1)

  {

       i=i/2;

       i=i/3;

       i=i/5;

       i=i*10;

       i=i-10;

}

}
I am getting actual answer as  $\log _3n$+ n/10 = O(n).
Please explain briefly.
retagged by

1 Answer

4 votes
4 votes
Let's study your code

while(i>=1)

  {

       i=i/2;

       i=i/3;

       i=i/5;

       i=i*10;

       i=i-10;

}

the expression i=i/2,i=i/5 and i=i*10 will together get nullify

So I can rewrite your code as

while(i>=1)

  {

      

       i=i/3;

     

       

       i=i-10;

}

Now, the running time depends on how the sub-problem size decreases every time.

Initially it will be n.

After $1^{st}$ iteration it will be  $\frac{n}{3}-10$

After second iteration it will be $\frac{ \frac {n}{3}-10}{3}-10$ = $\frac{n}{3^2}-10(1+\frac{1}{3})$

So, after $K^{th}$ iteration your problem size would be

$\frac{n}{3^k}-10(1+\frac{1}{3}+\frac{1}{3^2}+......+\frac{1}{3^{k-1}})$

Simplfiy this and you will get

$\frac{n}{3^k}-10(\frac{1-\frac{1}{3^k}}{1-\frac{1}{3}})$

and this becomes $\frac{n}{3^k}+15(1-\frac{1}{3^k})$

For purpose of complexity, you can ignore the term $15(1-\frac{1}{3^k})$ as it will be a constant

So, the loop will terminate when $\frac{n}{3^k}=1$ which makes k=$\log_3n$

So your complexity is $O(log_3n)$
edited by

Related questions

0 votes
0 votes
0 answers
2
0 votes
0 votes
1 answer
3
NeelParekh asked Jul 27, 2023
279 views
If an array is split in the form of increasing and decreasing order then what is TC to find minimum element in the array?
2 votes
2 votes
1 answer
4
h4kr asked Dec 30, 2022
472 views
What is the correct time complexity in $\theta()$ ?