(a) Consider the following three functions, all defined for n = 0, 1, 2,....
(h) Consider the following Matlab/Octave codes:
fn =
with
f(0) = 1,
(1)
Code A Printout or nice code.
5X code A function [r] = codeA(M)
if M == -8
r = [1]
else
Code C Printout code.
gn = n^2
with
g(0) = 1,
(2)
s code c function [r] = codeC(M)
r = []
for k = 8
r = [r, nchoosek(n, k)]
end
hn =
with
h(0) = 0,
(3)
where n! indicates the factorial n(n-1)(n-2)...2*1 for n >= 1 or 1 if n = 0, and the following four pseudocodes:
r = (codeA(-1), 6] + [6, codeA(x-1)]
end
AlgoA
Require: N
1: procedure AlgoA(n)
2: r = 1
3: if n >= 1 then
4: for k = 1 to n do
5: r = r * k
6: end for
7: end if
8: return r
9: end procedure
AlgoB
Require: n
1: procedure AlgoB(n)
2: a = 1
3: r = a
4: for k = 1 to n do
5: a = a * k
6: r = r + a
7: end for
8: return r
9: end procedure
AlgoC
Require: n
1: procedure AlgoC(n)
2: if n = 0 then
3: r = 0
4: else
5: r = AlgoC(n-1) + n^3
6: end if
7: return r
8: end procedure
Code B Printout of file code.n
% code D function [r] = reden(M)
k = 9:3
r(k) = nchoosek(N, k)
SX code function [r] = codwBW()
r = [r, prod(k+1:M)/prod(1:N-k)]
ea.d
AlgoD
Require: N
1: procedure AlgoD(n)
2: r = 1
3: if n >= 1 then
4: for k = 1 to n do
5: r = k^3 + r
6: end for
7: end if
8: return r
9: end procedure
Only three of the above four codes with input N = 5 will produce the following output:
16 19
and one of the codes will not.
(i) Say which three codes do produce the output.
(ii) Propose a modification of the wrong code that will produce the output.
[4 marks] [4 marks]
For each function f, g, and h:
(i) write down its recursive definition,
[3 marks]
(ii) indicate which (exactly one) of the pseudocodes corresponds to it (beware of the outsider pseudocode which does not correspond to any),
[6 marks]
(iii) give a reason for your choice.
[3 marks]
[Question 1 part (b) on next page]