GATE / CS ARCHIVE

GATE CSE 2013 / QUESTION 31

Returned value of nested loops

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2013 paper

GATE 2013, Q31 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 31, GATE 2013: For integer n, unknown initializes k=0; for i=n/2 through n inclusive, for j=2 while j≤n doubling each time, it adds n/2 to k; finally returns k. Choose growth of returned value: AΘ(n²), BΘ(n²log n), CΘ(n³), DΘ(n³log n). Integer divisions truncate; asymptotics use no-overflow mathematical arithmetic.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

The outer loop runs Θ(n) times and the doubling inner index takes Θ(log n) iterations for each. Each iteration adds a value Θ(n) to the accumulator. Thus the returned value is Θ(n² log n), B. The number of loop-body executions, and hence the usual unit-cost running time, is only Θ(n log n); the question asks for the value returned. This asymptotic calculation uses mathematical integers or assumes no integer overflow, rather than literal fixed-width C behavior for arbitrarily large n.

There are n−floor(n/2)+1 outer iterations. For n≥2 the inner values are 2, 4,…, 2^floor(log2 n), so there are floor(log2 n) inner iterations each time. Each contributes floor(n/2), giving the exact mathematical-integer value [n−floor(n/2)+1]floor(log2 n)floor(n/2). Multiplying these three orders gives Θ(n²log n). A running-time answer would omit the magnitude added per iteration and would be a different question.

Original paper, page 7 · Answer key