Skip to content
Related Articles
Open in App
Not now

Related Articles

Algorithms | Analysis of Algorithms | Question 18

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 29 Jul, 2021
Improve Article
Save Article

Consider the following function

 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;

What is the return value of the function? (GATE CS 2013)

(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: In the below explanation, '^' is used to represent exponent:
The outer loop runs n/2 or Theta(n) times.
The inner loop runs (Logn) times (Note that j is multiplied by 2 in every iteration).
So the statement "k = k + n/2;" runs Theta(nLogn) times.
The statement increases value of k by n/2.
So the value of k becomes n/2*Theta(nLogn) which is Theta((n^2) * Logn).

Quiz of this Question

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!