- 4.
procedure max(a1,a2,...,an : integers)
if n = 1 then max(a1,a2,...,an) := a1
else
begin
m := max(a1,a2,...,an-1)
if m > an then max(a1,a2,...,an) := m
else max(a1,a2,...,an) := an
end
- 6.
procedure power(x,n,m: positive integers)
if n = 1 then power(x,n,m) := x mod m
else power(x,n,m) := (x power(x,n-1,m)) mod m
- 8. Input is a list a1,...,an of integers, call it L. If n = 1,
then the output is that the mode is a1 and it appears 1 time. For n >
1, form a new list L' by deleting from L the term an and all terms in
L equal to an. Let k be the number of terms deleted. If k = n, then
the output is that the mode is an and it appears n times. Otherwise,
apply the algorithm recursively to L', obtaining a mode m, which
appears t times. Now if t >= k, then the output is that the mode is m
and it appears t times; otherwise the output is that the mode is an
and it appears k times.
- 12.
procedure fastpower(n: positive integer, a: real number)
if n = 1 then fastpower(n,a) := a
else if n is even then fastpower(n,a) := fastpower(n/2,a)^2
else fastpower(n,a) := a fastpower((n-1)/2,a)^2
- 14. To compute f7, algorithm 7 requires f8 - 1 = 20 additions,
and algorithm 8 requires 7 - 1 = 6 additions.
- 20. The iterative algorithm is much more efficient. If we compute
with the recursive algorithm, we end up computing the small vlues
over and over and over again. Try it for n = 5.