Awesome q2a theme
0 votes
62 views
int s=0;
for(int b=1;b<=n;b*=2)
{
    for(int i=0;i<b;i++)
    {
        for(int j=0;j<n;j+=2)
        {
            s=s+j;
        }
        
        for(int j=1;j<n;j*=2)
        {
            s=s+j;
        }
    }
}

What is the TC of above code? Please illustrate the sigma summation method.

in Algorithms by (403 points) | 62 views
0
is it $O\left ( n^{3} \right )?$
0
They've given O(n^2)
0

1 Answer

+2 votes
Best answer

I think its $O(n^2)$.

The inner most for loops:

for(int j=0;j<n;j+=2)

Takes $O(n)$

for(int j=1;j<n;j*=2)

Takes $O(logn)$

Since they are in sequence : $O(n) + O(logn) = O(n)$

Now evaluate outside in:

b 1 2 4 8 .... .... .... .... $2^k = n$
i ( 0 to b) 1 time 2 times 4 times 8 times         $2^k$ times
innermost $O(n)$ $O(n)$ $O(n)$ $O(n)$         $O(n)$
Total n times 2n times 4n times 8n times         $2^k * n$ times

 

Sum up the total number of times:

$ = n + 2n + 4n+ 8n+......+2^k *n$

$ = n (1 + 2 + 4 + 8 + ...... + 2^k)$

Also $2 ^k = n \implies k = log n$

$ = n (1 + 2 + 4 + 8 + ...... log n\:times)$

Apply the GP summation $ a*\frac{(r^p - 1)}{r -1}$, here $a = 1, r = 2, p = log n$

$ = n*(1 *\frac{2^{logn}-1}{2-1})$

$ = n*(1 *\frac{n-1}{1})$

Which is clearly $O(n^2)$

by (1.9k points)
selected by
0

@shashin

In this line

for(int j=0;j<n;j+=2)

It is sum of A.P. How it could be O(n)?? Sum of A.P. must be $O(n^2)$, right??

0

@srestha they are asking Time Complexity, not the value of variable s.

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
Top Users 2020 Aug 10 - 16
  1. Arkaprava

    404 Points

  2. jayeshasawa001

    198 Points

  3. SarathBaswa

    126 Points

  4. Ashutosh777

    67 Points

  5. toxicdesire

    20 Points

  6. Nilabja Sarkar

    12 Points

  7. premu

    10 Points

  8. iarnav

    7 Points

  9. Jhumpa_Sarma

    6 Points

  10. Patel0967

    6 Points

Weekly Top User (excluding moderators) will get free access to GATE Overflow Test Series for GATE 2021
Welcome to GATE CSE Doubts, where you can ask questions and receive answers from other members of the community.
Top Users Aug 2020
  1. Arkaprava

    404 Points

  2. jayeshasawa001

    203 Points

  3. Mellophi

    156 Points

  4. Ashutosh777

    143 Points

  5. SarathBaswa

    126 Points

  6. anurag sharma

    49 Points

  7. toxicdesire

    20 Points

  8. shashankrustagi2021

    16 Points

  9. premu

    16 Points

  10. Kushagra गुप्ता

    15 Points

7,769 questions
1,977 answers
11,275 comments
95,111 users