GATE | GATE-CS-2014-(Set-1) | Question 51
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
(A) Half of the product of the 3 consecutive integers.
(B) One-third of the product of the 3 consecutive integers.
(C) One-sixth of the product of the 3 consecutive integers.
(D) None of the above.
Answer: (C) Explanation: The statement “D = D * 3” is executed n*(n+1)*(n-1)/6 times. Let us see how.
For i = 1, the multiplication statement is executed (n-1) + (n-2) + .. 2 + 1 times.
For i = 2, the statement is executed (n-2) + (n-3) + .. 2 + 1 times
………………………..
……………………….
For i = n-1, the statement is executed once.
For i = n, the statement is not executed at all
So overall the statement is executed following times
[(n-1) + (n-2) + .. 2 + 1] + [(n-2) + (n-3) + .. 2 + 1] + … + 1 + 0
The above series can be written as
S = [n*(n-1)/2 + (n-1)*(n-2)/2 + ….. + 1]
The sum of above series can be obtained by trick of subtraction the series from standard Series S1 = n2 + (n-1)2 + .. 12. The sum of this standard series is n*(n+1)*(2n+1)/6
S1 – 2S = n + (n-1) + … 1 = n*(n+1)/2
2S = n*(n+1)*(2n+1)/6 – n*(n+1)/2
S = n*(n+1)*(n-1)/6
The above solution is relies on a trick to obtain the sum of the series, but there is a much more straightforward way of obtaining the same result :
For i = 1, the multiplication statement is executed (n-1) + (n-2) + .. 2 + 1 times.
For i = 2, the statement is executed (n-2) + (n-3) + .. 2 + 1 times
Therefore, for each i, the number of times the statement is executed is:
This is the sum of n natural numbers from 1 to n – i. Therefore, it can be simplified to:
Multiplying, we will get the following:
Now, this is the number of times the statement will be executed for each i. Therefore, in total, the number of times the statement will be executed is:
Ignore the half for the moment. Expanding the summation is simple. You can distribute it across the expression to get this:
Using the formulae for sum of n natural numbers and the sum of squares of n natural numbers, we get:
Simplifying further and taking n/6 as a common term will give you:
Now, take 2 as the common term and use it to cancel out the half that we ignored before. This gives you:
Finally, using a2-b2, you get the required answer:
This should make the solution clear to you now!
Quiz of this Question
Last Updated :
11 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...