Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

GATE | GATE CS 2013 | Question 31

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Consider the following function: 

C




int unknown(int n) {
    int i, j, k = 0;
    for (i  = n/2; i <= n; i++)
        for (j = 2; j <= n; j = j * 2)
            k = k + n/2;
    return k;
 }


(A)

\\Theta(n^2)

(B)

\\Theta(n^2Logn)

(C)

\\Theta(n^3)

(D)

\\Theta(n^3Logn)

(A)

A

(B)

B

(C)

C

(D)

D


Answer: (B)

Explanation:

Here we have to tell the value of k returned not the time complexity. 
 

for (i  = n/2; i <= n; i++)
        for (j = 2; j <= n; j = j * 2)
            k = k + n/2;
    return k;

The outer loop runs n/2 times 
The inner loop runs logn times.(2^k = n => k = logn). 
Now looking at the value of k in inner loop, n is added to k, logn times as the inner loop is running logn times. 
Therefore total time complexity is inner multiplied with outer loop complexity which (n for outer and nlogn for inner) n*logn. 

Therefore the value of k after running the inner loop one time is  n^2logn.
See https://www.geeksforgeeks.org/algorithms-analysis-of-algorithms-question-5/
This solution is contributed by Parul Sharma.
 


Quiz of this Question
Please comment below if you find anything wrong in the above post

My Personal Notes arrow_drop_up
Last Updated : 31 May, 2021
Like Article
Save Article
Similar Reads