You are on page 1of 2

Tutorial 6

FIT 1029 Algorithmic Problem Solving


3 April 2014 Prepared by Julian Garca
The objectives of this tutorial are:
To understand recursion.
To understand how stacks can be used to implement recursion.
This tutorial will also provide an opportunity to go through the mid semester test.
Task 1
Write down the pseudocode of an algorithm to compute the factorial
1 1
Factorial of n is often denoted n!. For
example 5! = 5 4 3 2 1 = 120.
of N, using recursion.
Task 2
On week 2 we reviewed an algorithm to compute the greatest com-
mon divisor of two positive integers. This was Euclids algorithm
and the owchart is on the right margin. Try to write down this al-
gorithm using recursion. Compare your recursive version with the
non-recursive version discussed on week 2.
Input: Two integers a and b
Output: GCD(a, b)
a = q*b + r
a = q*b + r
EuclidGdc(a, b)
Find the remainder
that results from
dividing a over b.
Set the value of a to
what the value of b is
Set the value of b to
what the value of r is
Name:
Is r = 0?
Output
b
a!b
b!r
r! a mod b
Yes
No
Task 3
In how many ways can you tile a 1xN rectangle with 1 2 and
1 1 tiles?
Design an algorithm to compute this number recursively.
Figure 1: A tiling problem.
tutorial 6. fit 1029 algorithmic problem solving 2
Task 4
Consider the following modules...
Algorithm 1 g(n)
1: input: A non-negative integer n
2: output: An integer
3: return f(n, 0, 1)
Algorithm 2 f(n, m, p)
input: Three non-negative integers n, m, p
2: output: An integer
if n =0 then
4: return m
else
6: return f(n-1, p, m+p)
end if
Compute g(7) and show the result of each module call in the order
they are computed.
Describe what you believe g(n) is calculating.
Task 5
Write an iterative algorithm that uses a stack to calculate the n th
number of the series
2
: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, . . . ; for n > 2.
2
This is known as the Lucas series
Task 6
Write down a recursive algorithm to nd a root of a continuous
function f (x) in a given interval [a, b]. Specify any assumptions if
required.

You might also like