3,912 views
0 0 votes

What will be time complexity:

main()
{
    int sum=0;
    for(int bound=1;bound<=n;bound*=2)
    {
        for(int i=0;i<bound;i++)
        {
            for(j=0;j<n;j+=2)
            {
                sum+=j;
            }
            for(int j=1;j<n;j*=2)
            {
                sum*=j;
            }
        }
    }
}

I think every for loop is participating to find T.C.

something*2 means why will it run upto $log n$ and not upto $\frac{n}{2}$

1 Answer

Best answer
3 3 votes
for(int bound=1;bound<=n;bound*=2)
{
     for(int i=0;i<bound;i++)
     {
         for(j=0;j<n;j+=2) ====> O(n/2)
         {
             sum+=j;
         }
         for(int j=1;j<n;j*=2)===> O(logn)
         {
           sum*=j;
         }
     }
}

 

O($\frac{n}{2}$) + O(log2n) = O(n) + O(log2n) = O(n)

 

for(int bound=1;bound<=n;bound*=2)
{
     for(int i=0;i<bound;i++)
     {
         O(n)
     }
}

 

let n= 2k, then

bound = 1 ===> i runs one time i.e., i=0

bound = 21 ===> i runs 21 times i.e., i=0,i=1

bound = 22 ===> i runs 22 times i.e., i=0,i=1,i=2,i=3

......

bound = 2k ===> i runs 2k times i.e., i=0,i=1,i=2,....i=(n-1)

 

===> total times = 20 + 21 + 22 + ...... + 2k = 2(k+1) - 1 = 2.2k - 1 = 2 n - 1. ===> O(n)

But each time it runs O(n) times

∴ Total Time Complexity = O(n) . O(n) = O(n2)

selected by
Position:
Show:

Related questions

1 1 vote
1 answers 1 answer
1.4k
1.4k views
shikharV asked Nov 15, 2015
1,371 views
The answer to the above problem is A but I am expecting it to be D as constant amount of work is required to solve each subproblem.27Define $A_{i j}^{(k)}=\min \left(A_{i...
0 0 votes
0 0 answers
499
499 views
saket jaiswal asked Jan 18, 2025
499 views
Q) Find time complexity of this code:int n;int sum;for (int i = 1; i < n; i++) { for (int j = 0; j < i * i; j++) { if (j % i == 0) { ...
0 0 votes
1 1 answer
1.8k
1.8k views
Rackson asked Jan 12, 2019
1,833 views