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!
Please Login to comment...