CS 106 lecture 5, 6 notes
Recursive functions
A recursive function is a function that calls itself. These arise naturally from many mathematical
definitions, e.g. factorial:
n! = n(n‐1)(n‐1) … 1 = n(n‐1)! Where 0! = 1
An iterative solution would be:
function
[ fac ] = faci( n )
% faci computes n! iteratively
%
works for 0 because loop does not execute
fac = 1;
for
i = 1:n
fac = fac*i;
end
end
A recursive solution on the other hand is:
function
[ fac ] = facr( n )
% facr computes n! recursively
%
if
n == 0
% the escape fro the iteration
fac = 1;
else
fac = n*facr(n1);
end
end
A recursive function needs some step which reduces the problem and code that causes the recursion to
come to a stop.
Recursion is often a quick way to write a function, especially if it is tied to a mathematical definition, but
sometimes it is simply the easiest way to break down a problem though perhaps not the most efficient.
A recursive function that pushes the limits of computers quite quickly is the harmless looking
Ackermann function
n + 1
if m = 0
A(m,n) =
A(m‐1,1)
if m > 0 and n = 0
A(m‐1,A(m,n‐1))
if m > 0 and n > 0
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentTry writing it as a recursive function.
Triangles
In Project Euler (projecteuler.net) there is a problem where you are given 1000 triangles in a file, as
1000 lines with three pairs of points per line.
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '13
 P.Dobosh
 Recursion, Dice, recursive function

Click to edit the document details