Question

Consider the following pseudo code. What is the total number of multiplications to be performed?

D = 2
for i = 1 to n do
    for j = i to n do
        for k = j + 1 to n do
            D = D * 3
Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2014 answer key

Solution

Count the number of iterations of the three nested loops by analyzing the loop index inequalities.

In the given pseudocode:

  • Loop 1: i runs from 11 to nn.
  • Loop 2: j runs from i to nn.
  • Loop 3: k runs from j+1j + 1 to nn.
    Inside the innermost loop, one multiplication D = D * 3 is performed per iteration.

The number of multiplications is the number of integer triples (i,j,k)(i, j, k) satisfying:

1≤i≤j<k≤n1 \le i \le j < k \le n

Let us split this condition into two disjoint cases based on whether i<ji < j or i=ji = j:

  1. Case i<j<ki < j < k:
    This corresponds to choosing 3 distinct indices from {1,2,…,n}\{1, 2, \dots, n\}:

    Count1=(n3)=n(n−1)(n−2)6\text{Count}_1 = \binom{n}{3} = \frac{n(n-1)(n-2)}{6}
  2. Case i=j<ki = j < k:
    Here ii and jj are identical, so we choose 2 distinct values (the common value i=ji = j, and kk):

    Count2=(n2)=n(n−1)2=3n(n−1)6\text{Count}_2 = \binom{n}{2} = \frac{n(n-1)}{2} = \frac{3n(n-1)}{6}

Total number of multiplications:

Total=(n3)+(n2)=n(n−1)(n−2)+3n(n−1)6\text{Total} = \binom{n}{3} + \binom{n}{2} = \frac{n(n-1)(n-2) + 3n(n-1)}{6}
Total=n(n−1)[(n−2)+3]6=(n−1)n(n+1)6\text{Total} = \frac{n(n-1)[(n-2) + 3]}{6} = \frac{(n-1)n(n+1)}{6}

Notice that (n−1)(n-1), nn, and (n+1)(n+1) are three consecutive integers.
Therefore, the total number of multiplications is 'one-sixth of the product of the 3 consecutive integers' (Option C).

Final answer

C

Common trap

Assuming i<j<ki < j < k strictly, which gives only (n3)\binom{n}{3}, forgetting that jj starts at ii.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2014 Computer Science and Information Technology (CS) Session 1
Question
52 of 65, printed as CS Q.42
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.