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
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:
iruns from to . - Loop 2:
jruns fromito . - Loop 3:
kruns from to .
Inside the innermost loop, one multiplicationD = D * 3is performed per iteration.
The number of multiplications is the number of integer triples satisfying:
Let us split this condition into two disjoint cases based on whether or :
-
Case :
This corresponds to choosing 3 distinct indices from : -
Case :
Here and are identical, so we choose 2 distinct values (the common value , and ):
Total number of multiplications:
Notice that , , and are three consecutive integers.
Therefore, the total number of multiplications is 'one-sixth of the product of the 3 consecutive integers' (Option C).
C
Assuming strictly, which gives only , forgetting that starts at .
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.